none
Lock/Unlock file on a network share RRS feed

  • Question

  • I think that want I need to do is a very common problem but I failed to find a solution.

    I need to update a file on a network share from different computers. I need to read the current state, update it and write back. And this operation should be atomic. I need to be sure that only one client is using the file at a time.

    Could you, please help me?

    Thanks a lot.

    Friday, March 30, 2012 2:19 PM

Answers

All replies

  • The FileStream class which is used to read and write files has many different constructors.

    Look at this one:

    http://msdn.microsoft.com/en-us/library/5h0z48dh.aspx

    You can use the FileMode, FileAccess, and FileShare parameters to control how the operating system locks (or does not lock) the file you're currently working with.

    Evan

    • Proposed as answer by servy42 Friday, March 30, 2012 5:10 PM
    • Marked as answer by Jason Dot Wang Wednesday, April 11, 2012 5:18 AM
    Friday, March 30, 2012 2:43 PM
  • As Evan suggested you can lock the file.

    For your second problem, you can use a lock keyword to make sure multiple threads are not entering the file access routine.

    or

    Use exceptions to determine file in use or not.


    Resolving n Evolving in C# (http://jeanpaulva.com)

    Friday, March 30, 2012 2:47 PM
  • The FileStream class which is used to read and write files has many different constructors.

    Look at this one:

    http://msdn.microsoft.com/en-us/library/5h0z48dh.aspx

    You can use the FileMode, FileAccess, and FileShare parameters to control how the operating system locks (or does not lock) the file you're currently working with.

    Evan

    Thank you. I'll try this.
    Friday, March 30, 2012 5:07 PM