File is being used by another process in c#

拈花ヽ惹草 提交于 2019-12-12 10:04:34

问题


I am trying to delete a file in C#, however I am receiving a message that the file is used from another process. What I want to do is to check if the files exists and close it. I am using the following function in order to check if the file is open:

public static bool IsFileInUse(string path)
    {
        if (string.IsNullOrEmpty(path))
            throw new ArgumentException("'path' cannot be null or empty.", "path");

        try
        {
            using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read)) { }
        }
        catch (IOException)
        {
            return true;
        }

        return false;
}

and I am trying when the file is in use to close it:

bool checking = IsFileInUse(file );
File.Create(file ).Close();
if (File.Exists(file))
{
       File.Delete(file );
}

I got issues in File.Create line, I am receiving the message:

File is being used by another process.

EDIT: I am trying to use lock approach in order to delete the file. Am I suppose to delete the file inside a lock statement? How Can I use properly the lock statement?


回答1:


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.




回答2:


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.
  }



回答3:


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 );
     }
}


来源:https://stackoverflow.com/questions/35057709/file-is-being-used-by-another-process-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!