Search code examples
c#asp.net.netbiztalkstreamwriter

Can I ReadLock a file while I create/modify it using System.IO.File.WriteAllText() method?


I need to create a process that creates/modifies some text files in a folder. I am using below code to do that:

file = new System.IO.FileInfo(filePath);
file.Directory.Create(); 
System.IO.File.WriteAllText(file.FullName, "Some text...");

I have a Biztalk queue that looks into the text files in the folder every 2 minutes and picks up the files to process them. I want to lock the files when I am creating/modifying so that Biztalk wont try to process those files. How can I achieve this?

I read about Transactional NTFS in windows which will let me create Transaction context but windows documentation says this feature will deprecated and recommends not to use it.


Solution

  • To acquire an exclusive lock you can use the file stream to do so

            using (FileStream fs = new FileStream("Test.txt", FileMode.Append, FileAccess.Write, FileShare.None))
            {
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    sw.WriteLine("test");
                }
            }
    

    This way you are locking the file exclusively for the current file stream. Any other application or even a new instance of file stream from another thread within the same application attempts to read or write to the file will be denied by the operating system.