[C#.Net]判断文件是否被占用的两种方法
2017-08-14 10:45
621 查看
第一种方法:API
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("没有被占用!");
}
第二种 FileStream
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没有使用
}
引用自:http://www.cnblogs.com/masonlu/p/6867122.html
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("没有被占用!");
}
第二种 FileStream
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没有使用
}
引用自:http://www.cnblogs.com/masonlu/p/6867122.html
相关文章推荐
- [C#.Net]判断文件是否被占用的两种方法
- [C#.Net]判断文件是否被占用的两种方法
- C# 判断文件是否被占用的两种方法
- C# 判断文件是否被占用的两种方法
- C# 判断文件是否被占用的两种方法
- C# 判断文件是否被占用的两种方法
- C# 判断文件是否被占用的可以用下面的方法
- C#判断文件是否被打开占用
- C#判断文件是否被打开占用
- vba判断文件是否存在的两种方法
- .net C# 如何判断一个对象是否具有某个方法
- C#判断文件是否被打开占用
- c#创建xml读取xml方法并判断文件目录以及文件是否存在
- C#判断文件是否被打开占用
- 在C#.net中做页面上传的程序。用Dhtml的控件:(创建文件上载控件,该控件带有一个文本框和一个浏览按钮。)和类HtmlInputFile的两种方法
- C#判断文件是否存在方法
- C#判断硬盘上的文件是否存在方法
- c# 文件操作 判断文件是否为空的方法
- C#判断文件是否被打开占用
- C#判断硬盘上的文件是否存在方法