Hi liubin,
你可以尝试用winapi来准确的检测异常是否文件被占用。
下面是具体的代码。
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern SafeFileHandle CreateFile(string lpFileName,
FileSystemRights dwDesiredAccess, FileShare dwShareMode, IntPtr
securityAttrs, FileMode dwCreationDisposition, FileOptions
dwFlagsAndAttributes, IntPtr hTemplateFile);
const int ERROR_SHARING_VIOLATION = 32;
static void Main(string[] args)
{
FileStream file = null;
FileStream file1 = null;
string fileName = "D:\\Data.txt";
try
{
file = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite); //file is opened
//you use the file here
file1 = new FileStream(fileName, FileMode.Open, FileAccess.Read);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
SafeFileHandle fileHandle =
CreateFile(fileName, FileSystemRights.Modify,
FileShare.Write, IntPtr.Zero,
FileMode.OpenOrCreate, FileOptions.None, IntPtr.Zero);
if (fileHandle.IsInvalid)
{
if (Marshal.GetLastWin32Error() ==ERROR_SHARING_VIOLATION)
{
Console.WriteLine("File is in use");
}
}
fileHandle.Close();
}
根据下面的链接,你可以找到当数字为32时,对应的异常是‘The process cannot access the file because it is being used by another process.’.
System Error Codes (0-499)
希望对你有所帮助。
Best Regards,
Jack
MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to
MSDN Support, feel free to contact MSDNFSF@microsoft.com.