[2.0] how to unlock the file?
Howdy and Merry Christmas folks,
I wrote a small filewatcher service that looks for a file on the file server every once in 30 minutes.
If a file exists, it checks if the file has been locked by other user. I wrote the following code to check that. But it looks like FileLocked method is not releasing the connection to the file. The moment this method is called, the file gets locked for any other user (ofcourse the file can be opened in read only mode). can some suggest me what I should do to release the file?
public bool FileLocked(string file)
{
StreamReader sreader;
try
{
sreader = File.OpenText(file);
return false;
}
catch (Exception ex)
{
//TODO: write to the log file that other user has opened the file
return true;
}
finally
{
sreader = null;
}
}
Re: [2.0] how to unlock the file?
Setting a variable to null has no effect other than to make that variable no longer refer to that object. The object still exists. In your case setting the variable to null is completely pointless because it loses scope immediately after anyway. You need to Close the StreamReader to release the file. Also, you don't need a StreamReader at all because you're not reading the stream. Just use a FileStream instead, which you create by calling File.Open.