C# 判断文件是否被占用的可以用下面的方法

来源:互联网 发布:ccf大数据专家委员会 编辑:程序博客网 时间:2024/05/16 05:22
先判断一下文件是否已经被打开了(占用),如果已经被打开了,就别再去打了,可以给出你自己的提示(或根据自己的需要进行其它的处理)。

   

       
       C# 判断文件是否被占用的可以用下面的方法
       
   

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
方法一:
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:\temp\temp.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("没有被占用!");  
}

方法二:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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没有使用  
}
1 0
原创粉丝点击