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

    第一种方法:
    
    using System.IO;
    using System.Runtime.InteropServices;
    
    [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 readonly IntPtr HFILE_ERROR = new IntPtr(-1);
    private void button1_Click(object sender, EventArgs e)
    {
        string vFileName = @"c:	emp	emp.bmp";
        if (!File.Exists(vFileName))
        {
            MessageBox.Show("文件都不存在!");
            return;
        }
        IntPtr vHandle = _lopen(vFileName, OF_READWRITE | OF_SHARE_DENY_NONE);
        if (vHandle == HFILE_ERROR)
        {
            MessageBox.Show("文件被占用!");
            return;
        }
        CloseHandle(vHandle);
        MessageBox.Show("没有被占用!");
    }
    
    
    第二种方法:
    
    public static bool IsFileInUse(string fileName)
     {
            bool inUse = true;
    
            FileStream fs = null;
            try
            {
    
                fs = new FileStream(fileName, FileMode.Open, FileAccess.Read,
    
                FileShare.None);
    
                inUse = false;
            }
            catch
            {
    
            }
            finally
            {
                if (fs != null)
    
                    fs.Close();
            }
            return inUse;//true表示正在使用,false没有使用
    }
    

      

  • 相关阅读:
    一个java点菜程序
    团队成员
    CentOS tomcat普通用户执行配置安装
    varnish的监控和调试
    组播协议和组播路由
    AVAYA加外线DID,30B+D
    vi技巧
    CentOS开启Telnet服务
    juniper 虚拟路由
    DOS批处理下操作telnet实现自动远程登录操作
  • 原文地址:https://www.cnblogs.com/waw/p/3261786.html
Copyright © 2011-2022 走看看