C# 判断文件是否打开
以下是C#中判断文件是否打开的几种方法:
- 使用
FileStream类
public static bool IsFileInUse(string filePath)
{
try
{
using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None))
{
stream.Close();
}
}
catch (IOException)
{
return true;
}
return false;
}
这种方法会以指定的访问模式尝试打开文件,如果文件正在被其他进程使用,则会抛出IOException异常。如果文件未被使用,则方法返回false。
- 使用
Process类
public static bool IsFileInUse(string filePath)
{
var processName = Path.GetFileNameWithoutExtension(filePath);
if (Process.GetProcessesByName(processName).Any(p => p.MainModule.FileName.Equals(filePath, StringComparison.OrdinalIgnoreCase)))
{
return true;
}
return false;
}
这种方法将通过检查是否存在正在运行以指定文件名命名的进程来检查文件是否正在使用。
- 使用
FileAccess.Read和FileShare.ReadWrite
public static bool IsFileInUse(string filePath)
{
try
{
using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
stream.Close();
}
}
catch (IOException)
{
return true;
}
return false;
}
这种方法在打开文件时使用FileAccess.Read访问模式和FileShare.ReadWrite共享模式。如果文件正在被其他进程占用,则尝试打开该文件的进程可能已打开文件以进行读写,而不仅仅是读取。因此,使用此访问和共享模式将仅对其他进程使用该文件的情况产生有效的锁定效果。

浙公网安备 33010602011771号