My C # application is blocking a file, how can I find where it does it?

I write code that checks the file path, calculates the hash (SHA1) and copies them. I made sure that I do not block them, for example, using

public static string SHA1(string filePath) { var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); var formatted = string.Empty; using (var sha1 = new SHA1Managed()) { byte[] hash = sha1.ComputeHash(fs); foreach (byte b in hash) { formatted += b.ToString("X2"); } } return formatted; } 

So, how can I find in Visual Studio where it locks a file?

+4
source share
4 answers

Can you keep the syntax above and give it a try?

 using(var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { //Your code goes here. } 
+15
source

There is a small soft: process explorer window in which you can find which process has a file descriptor:

http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx

+4
source

Blocking usually occurs whenever you create a file stream in a file without subsequently closing this stream. If you do not call fs.Close(); into your code, your application will keep the file open (and thus locked).

You can wrap this in a try-finally block or try the code that Shiva Gopal posted.

+3
source

It is assumed that opening a file stream only with FileAccess.Read will not lock the file. the file is locked while it is open for file operation and has not been closed.

A FileStream does not close the open file until the FileStream is garbage collected or you explicitly call its Close or Dispose method. Or insert such an explicit call as soon as you are done with the file that opens. Or wrap the use of FileStream in a using statement, which implies calling Dispose , as other answers suggest.

+1
source

All Articles