Results 1 to 2 of 2

Thread: [2.0] how to unlock the file?

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Oct 2003
    Posts
    436

    [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;

    }



    }

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    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.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width