views:

151

answers:

4

I'm writing code that check files path calculate hash (SHA1) and copy them. I made sure that I do not lock them like 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 I can, in Visual Studio, find where it does lock the file?

+4  A: 

There is a little windows soft : process explorer and in this you can find which process has an handle on a file :

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

remi bourgarel
+14  A: 

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

using(var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
//Your code goes here.
} 
Siva Gopal
+1: Just to clarify: the `using` block calls `fs`'s `Dispose()` method when it exits the scope, closing the stream and releasing unmanaged resources. Using a `using` block like this means you don't have to manually call `fs.Close()` after you have finished with the stream and it works with all types with an `IDisposable` interface.
Callum Rogers
You are right. Because, ideally clean up of unmanaged resources(suppose if the class is going to use unmanaged resources) should already been handled inside the Dispose() method of Type/Class.
Siva Gopal
+3  A: 

Locking usually happens whenever you create a file stream on a file without later closing that stream. Unless you call fs.Close(); in your code, your application will keep the file open (and thus locked).

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

Thorsten Dittmar
+1  A: 

You assumption that opening the file stream with just FileAccess.Read will not lock the file is faulty; the file is locked while it has been opened for a file operation and has not been closed.

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

peSHIr