方法1:打开看看就知道了
/// <summary>
/// 判断一个文件是否正在使用函数;打开看看就知道了
/// </summary>/// <param name="fileName">将要判断文件的文件名</param>
/// <returns> bool</returns>
{
bool inUse = true ;
if (File.Exists(fileName))
{
FileStream fs = null ;
try
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None);
inUse = false ;
}
catch (Exception e)
{
Console.WriteLine(e.Message.ToString());
}
finally
{
if (fs != null )
{
fs.Close();
}
}
return inUse; //true表示正在使用,false没有使用
}
else
{
return false; //文件不存在则一定没有被使用
}
}
方法2:调用VC库
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("没有被占用!");
}