zoukankan      html  css  js  c++  java
  • C# WinForm 检测文件是否被占用

    #region 检测文件状态及操作方式选择
    [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="FileNames">要检测的文件</param>
    /// <returns>true可用,false在用或只读</returns>
    public static bool CheckFilesState(string fileName)
    {
        if (!File.Exists(fileName))
            return true;//文件不存在
        if ((File.GetAttributes(fileName) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
            return false;       //文件只读
        IntPtr vHandle = _lopen(fileName, OF_READWRITE | OF_SHARE_DENY_NONE);
        if (vHandle == HFILE_ERROR)
            return false;       //文件被占用
        CloseHandle(vHandle);   //文件没被占用
        return true;
    }
    /// <summary>
    /// 检测文件是否只读或被使用,并由用户选择是否继续操作
    /// </summary>
    /// <param name="fileFullName">要检测的文件</param>
    /// <returns>true已在用,false未用</returns>
    public static bool FileHasOpened(string fileFullName)
    {
        bool lOpened = false;
        bool lRetry = true;
        do
        {
            if (!CheckFilesState(fileFullName))
            {
                if (DialogResult.Cancel == MessageBox.Show("文件只读或已经被打开,请处理后再操作!", "系统错误!", MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning))
                {
                    lRetry = false;
                    lOpened = true;
                }
            }
            else
                lRetry = false;
        } while (lRetry);
        return lOpened;
    }
    #endregion
  • 相关阅读:
    Centos7 安装RabbitMQ 3.6.1
    面向对象编程(类的绑定方法与非绑定方法)
    面向对象编程(封装、封装的意义、封装与扩展性、@property)
    函数式编程(__slots__)
    面向对象编程(实例属性、类属性)
    面向对象编程(获取对象信息)
    面向对象编程(继承、多态)
    函数式编程(访问限制)
    面向对象编程(类与实例)
    面向对象编程(基础简介)
  • 原文地址:https://www.cnblogs.com/hnllhq/p/13293740.html
Copyright © 2011-2022 走看看