locked
how to ensure a process has exclusive access to a network file? RRS feed

  • Question

  • The file is located in a network shared folder, and the process manipulates the file multiple times, opens it with appropriate share mode
    and save it in a short period of time. 
    During the process's execution, other process can also access the file, and this introduces an undesired race, which can potentailly corrupt the file.

    How to ensure that a process has exclusive access to a file during its execution time? So that other process (or more specifically, other instance of the same application running on other computers) can not acess the file, as if the first process open the file with exclusive access to the file and does not release the file until it exits?
    Tuesday, February 9, 2010 7:32 AM

All replies

  • hi kennyzx,

    try to read the file with the fileshare mode read.

    FileInfo fInfo = new FileInfo(myFileName);
    fInfo.Open(FileMode.Open, FielAccess.Read, FileShare.Read);
    FileStream fStream = fInfo.OpenRead();

    this should block any external access to the file, but you have further read permission to the file. Don't forget to dispose the stream, otherwise, you won't release your lock at the file. I hope this helps :-)

    Tuesday, February 9, 2010 9:37 AM
  • oral.polat,

    Sorry I leaved for several days on holiday and had no time to try out,
    I appreciate your help.
    Monday, February 22, 2010 2:59 PM