张文的博客

导航

C# 判断文件有没占用

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace AdminTools
{
    public static class FileTools
    {
        [DllImport("kernel32.dll")]
        private static extern IntPtr _lopen(string lpPathName, int iReadWrite);
        [DllImport("kernel32.dll")]
        private static extern bool CloseHandle(IntPtr hObject);
        private const int OF_READWRITE = 2;
        private const int OF_SHARE_DENY_NONE = 0x40;
        private static readonly IntPtr HFILE_ERROR = new IntPtr(-1);
        /// <summary>   
        /// 检查文件是否已经打开   
        /// </summary>   
        /// <param name="strfilepath">要检查的文件路径</param>          
        /// <returns>true文件已经打开,false文件可用未打开</returns>   
        public static bool FileUsing(string strfilepath)
        {
            string vFileName = strfilepath;
            // 先检查文件是否存在,如果不存在那就不检查了   
            if (!System.IO.File.Exists(vFileName))
            {
                return true;
            }
            // 打开指定文件看看情况   
            IntPtr vHandle = _lopen(vFileName, OF_READWRITE | OF_SHARE_DENY_NONE);
            if (vHandle == HFILE_ERROR)
            { // 文件已经被打开                   
                return true;
            }
            CloseHandle(vHandle);
            // 说明文件没被打开,并且可用  
            return false;
        }
    }
}

 

posted on 2014-03-05 16:07  张文的博客  阅读(751)  评论(0编辑  收藏  举报