File is being used by another process in c#

纵然是瞬间 提交于 2019-12-06 04:19:15
Adriano Repetti

Why do you suppose that a reading operation will fail if file is in use while a writing operation will not? File.Create() will fail exactly as new FileStream() failed before...

See also IOException: The process cannot access the file 'file path' because it is being used by another process.

Note that your check will fail if the other process didn't open that file exclusively (check FileShare enumeration): file may be open for shared reading, writing and sometimes even for deleting (for example you may be able to read concurrently but not writing however the other process may let you delete that file...).

To close an open file can be really disruptive for the other process, it may crash, nicely handle the problem or...anything else (silently ignore that error and produce random output, open file again and so on...) Is it possible to do it in C#? Yes with some P/Invoke...

1) Let's find the handle for the file you want to unlock. Use NtQuerySystemInformation() and enumerate all handles until you find the one that refers to that file.

2) Duplicate that handle to be valid in your own process using DuplicateHandle().

3) Close just create handle specifying DUPLICATE_CLOSE_SOURCE, it will close both your handle and the original one (of course if your process has enough permissions).

4) Check if file is really closed calling NtQuerySystemInformation() again, if not then you may need to directly close its parent process.

You have no need to check if the file exists, just try do delete it:

https://msdn.microsoft.com/en-us/library/system.io.file.delete(v=vs.110).aspx

If the file to be deleted does not exist, no exception is thrown.

Try and check the exception

  try {
    File.Delete(file);
  }
  catch (IOException) {
    // File in use and can't be deleted; no permission etc.
  }

In your code, you don't do anything with the IsFileInUse result.

This File.Create(file ).Close(); will also not close a file that is opened by another process. You need to close the process that has the file open, and if it is your own app, close the file handle before trying to delete the file.

bool checking = IsFileInUse(file );
File.Create(file ).Close();
if (!checking) 
{
     if (File.Exists(file))
     {
            File.Delete(file );
     }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!