none
How to lock or unlock a file using C#?

    Question

  • Hi,

    I am changing a file using my application. I have two buttons like "lock the file" and "Unlock the file" in my application. I want to lock or unlock the file when I click corresponding buttons. How can I do this task?

    Thanks in Advance,

    Wednesday, April 22, 2009 10:12 AM

Answers

  • You can use FileStream.Lock and FileStream.UnLock for locking the file.

    Check out this article on MSDN for Lock :
    http://msdn.microsoft.com/en-us/library/system.io.filestream.lock(VS.71).aspx

    Check out this article on MSDN for UNLock :
    http://msdn.microsoft.com/en-us/library/system.io.filestream.unlock(VS.71).aspx

    Hope this helps you!
    Sandeep Aparajit | http://sandeep-aparajit.blogspot.com | Mark useful posts as Answer/Helpful.
    Wednesday, April 22, 2009 10:18 AM
  • I'm guessing that the code for your unlock and lock buttons does not have access to the FileStream where you have locked the file? Do you want to unlock a file that has been locked elsewhere?
    Wednesday, April 22, 2009 12:37 PM
  •                 FileInfo fileInfo = new System.IO.FileInfo(pathToTheFile);
                    if (!fileInfo.IsReadOnly) fileInfo.IsReadOnly = true;
    
    This will set your file in ReadOnly state or not.

    Best regards, Sergiu
    Thursday, April 23, 2009 8:04 AM
  • I am using the following code to create a lock file

    fstreamLock =

    new FileStream(dblpath, FileMode.CreateNew, FileAccess.Write, FileShare.None);

     

    // add user info to the lock file

     

    sw.Write(

    StreamWriter sw = new StreamWriter(fstreamLock);

     "[UserInfo]\r\r\nUserName=" + System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString().Split(new char[] { '\\' })[1] + "\r\r\nMachine=" + System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString().Split(new char[] { '\\' })[0] + "\r\r\n\r\n"); File.SetAttributes(dblpath, File.GetAttributes(dblpath) | FileAttributes.Hidden);

     new FileStream(dblpath, FileMode.Open, FileAccess.Write, FileShare.Read);

    Also I want to check whether the file is currently using outside the application or not. Any idea?

    sw.Flush();

    sw.Close();

     

    fstreamLock =


    I still don't understand your requirement, but it should be quite simple to meet. Consider this: the only thread-safe way to check if a file is locked is to try and open it with the access you require--you must treat locking a file and opening a file as the same thing. How do you check if a file is locked for writing? By trying to open it with FileAccess.Write. If it is locked for writing, you will get an Exception, which you must handle as appropriate for your application. The same thing for reading--try to open the file with FileAccess.Read. So to check "whether the file is currently using outside the application" you need to try to open the file with a FileStream (with whatever FileAccess you need), and catch any exception that occurs.

    To prevent a file from being written to (to "lock" it) you must open it with FileShare.Read (which will still allow others to read it) or FileShare.None (which will not allow others to read or write it). The file will only be locked as long as you have it open. Once you close the file it is no longer locked. In your code you are opening the file, closing it, and then re-opening it. Between closing the file and opening it again, someone else (another thread etc) could come along and open the file for writing, which will mean your open call will fail (throw an exception).

    Using FileInfo.IsReadOnly is no good because anyone can easily change this back to false.

    • Marked as answer by Bin-ze Zhao Friday, April 24, 2009 7:28 AM
    Thursday, April 23, 2009 12:31 PM

All replies

  • When you open the file in your application using FileStream or any similar class you have option of opening it in SharingMode or not. If you open it in SharingMode file will not be locked. If you open it in Non-Sharing mode, file will be locked.

    Let me know if that is what you were looking for.

    thanks,
    Viral.
    Wednesday, April 22, 2009 10:17 AM
  • You can use FileStream.Lock and FileStream.UnLock for locking the file.

    Check out this article on MSDN for Lock :
    http://msdn.microsoft.com/en-us/library/system.io.filestream.lock(VS.71).aspx

    Check out this article on MSDN for UNLock :
    http://msdn.microsoft.com/en-us/library/system.io.filestream.unlock(VS.71).aspx

    Hope this helps you!
    Sandeep Aparajit | http://sandeep-aparajit.blogspot.com | Mark useful posts as Answer/Helpful.
    Wednesday, April 22, 2009 10:18 AM
  • Thanks Viral! You mean FileShare? I am using following code.

    FileStream 

    fstreamLock =

     

    fstreamLock =

    fstreamLock =

    new FileStream(dblpath, FileMode.Open, FileAccess.Write, FileShare.Read);

    But I could not access the file outside the application. I want to lock or unlock the whole file. Any idea?

    Regards,
    Jayahar


     

    Wednesday, April 22, 2009 10:41 AM
  • Yes, I mean the same and please have a look at

    http://msdn.microsoft.com/en-us/library/system.io.fileshare.aspx

    Snippet is as below:


    None Declines sharing of the current file. Any request to open the file (by this process or another process) will fail until the file is closed.
    Read Allows subsequent opening of the file for reading. If this flag is not specified, any request to open the file for reading (by this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions might still be needed to access the file.
    Write Allows subsequent opening of the file for writing. If this flag is not specified, any request to open the file for writing (by this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions might still be needed to access the file.
    ReadWrite Allows subsequent opening of the file for reading or writing. If this flag is not specified, any request to open the file for reading or writing (by this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions might still be needed to access the file.
    Delete Allows subsequent deleting of a file.
    Inheritable Makes the file handle inheritable by child processes. This is not directly supported by Win32.





    for setting up different permission level for the whole file.

    thanks,
    Viral.
    Wednesday, April 22, 2009 10:50 AM
  • Ofcourse.... you couldnt access the file outside the app. That's what a Lock... right? If this is not intended, what do want to do?
    Mark as answers if you find them helpful Guna
    Wednesday, April 22, 2009 12:17 PM
  • Initially I lock the file using the below code.

    FileStream = 
     fstreamLock =
    new FileStream(dblpath, FileMode.Open, FileAccess.Write, FileShare.Read);

    I have two buttons in my application like "lock" and "unlock". I want to lock or unlock the file when i click the corresponding buttons. Any idea? 

    Wednesday, April 22, 2009 12:25 PM
  • I'm guessing that the code for your unlock and lock buttons does not have access to the FileStream where you have locked the file? Do you want to unlock a file that has been locked elsewhere?
    Wednesday, April 22, 2009 12:37 PM
  • Yes It seems you are using local variables of FileStream in each methods.

    Post your code.
    Mark as answers if you find them helpful Guna
    Wednesday, April 22, 2009 12:45 PM
  • I am using the following code to create a lock file

    fstreamLock =

    new FileStream(dblpath, FileMode.CreateNew, FileAccess.Write, FileShare.None);

     

    // add user info to the lock file

     

    //

     

    StreamWriter sw = new StreamWriter(fstreamLock);

    sw.Write(

    "[UserInfo]\r\r\nUserName=" + System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString().Split(new char[] { '\\' })[1] + "\r\r\nMachine=" + System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString().Split(new char[] { '\\' })[0] + "\r\r\n\r\n");

    sw.Flush();

    sw.Close();

     

    File.SetAttributes(dblpath, File.GetAttributes(dblpath) | FileAttributes.Hidden);

    fstreamLock =

    new FileStream(dblpath, FileMode.Open, FileAccess.Write, FileShare.Read);

    Also I want to check whether the file is currently using outside the application or not. Any idea?

    Thursday, April 23, 2009 7:23 AM
  •                 FileInfo fileInfo = new System.IO.FileInfo(pathToTheFile);
                    if (!fileInfo.IsReadOnly) fileInfo.IsReadOnly = true;
    
    This will set your file in ReadOnly state or not.

    Best regards, Sergiu
    Thursday, April 23, 2009 8:04 AM
  • I am using the following code to create a lock file

    fstreamLock =

    new FileStream(dblpath, FileMode.CreateNew, FileAccess.Write, FileShare.None);

     

    // add user info to the lock file

     

    sw.Write(

    StreamWriter sw = new StreamWriter(fstreamLock);

     "[UserInfo]\r\r\nUserName=" + System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString().Split(new char[] { '\\' })[1] + "\r\r\nMachine=" + System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString().Split(new char[] { '\\' })[0] + "\r\r\n\r\n"); File.SetAttributes(dblpath, File.GetAttributes(dblpath) | FileAttributes.Hidden);

     new FileStream(dblpath, FileMode.Open, FileAccess.Write, FileShare.Read);

    Also I want to check whether the file is currently using outside the application or not. Any idea?

    sw.Flush();

    sw.Close();

     

    fstreamLock =


    I still don't understand your requirement, but it should be quite simple to meet. Consider this: the only thread-safe way to check if a file is locked is to try and open it with the access you require--you must treat locking a file and opening a file as the same thing. How do you check if a file is locked for writing? By trying to open it with FileAccess.Write. If it is locked for writing, you will get an Exception, which you must handle as appropriate for your application. The same thing for reading--try to open the file with FileAccess.Read. So to check "whether the file is currently using outside the application" you need to try to open the file with a FileStream (with whatever FileAccess you need), and catch any exception that occurs.

    To prevent a file from being written to (to "lock" it) you must open it with FileShare.Read (which will still allow others to read it) or FileShare.None (which will not allow others to read or write it). The file will only be locked as long as you have it open. Once you close the file it is no longer locked. In your code you are opening the file, closing it, and then re-opening it. Between closing the file and opening it again, someone else (another thread etc) could come along and open the file for writing, which will mean your open call will fail (throw an exception).

    Using FileInfo.IsReadOnly is no good because anyone can easily change this back to false.

    • Marked as answer by Bin-ze Zhao Friday, April 24, 2009 7:28 AM
    Thursday, April 23, 2009 12:31 PM