C#判断文件打开、占用的状态

来源:互联网 发布:mac zbrush 百度云 编辑:程序博客网 时间:2024/05/17 17:17

using System;
using System.IO;
using System.Runtime.InteropServices;

namespace Bn6.Packing.Common
{
    public class FileStatus
    {
        [DllImport("kernel32.dll")]
        public static extern IntPtr _lopen(string lpPathName, int iReadWrite);

        [DllImport("kernel32.dll")]
        public static extern bool CloseHandle(IntPtr hObject);

        public const int OF_READWRITE = 2;
        public const int OF_SHARE_DENY_NONE = 0x40;
        public static readonly IntPtr HFILE_ERROR = new IntPtr(-1);

        /// <summary>
        /// 获取文件状态(不存在返回-1;被占用返回1;正常返回0)
        /// </summary>
        /// <param name="fileFullName">文件全路径名</param>
        /// <returns></returns>
        public static int GetFileStat(string fileFullName)
        {
            if (!File.Exists(fileFullName))
                return -1;
            IntPtr vHandle = _lopen(fileFullName, OF_READWRITE | OF_SHARE_DENY_NONE);
            if (vHandle == HFILE_ERROR)
                return 1;
            CloseHandle(vHandle);
            return 0;
        }

    }
}