none
How to lock a file so when my c# program is reading it, nobody can move it. RRS feed

  • Question

  • I want to lock a file when my program is reading it: 

    Here is my code for reading the file:

    using(var stream = file.OpenRead())
    {
       using(var reader = new SteamReader(stream))
       {
          string line;
          while((line = reader.ReadLine()) != null)
          {
            //Do Something with the lines you read
          }
       }
    }

    How do I put an exclusive lock on the file?

    Thanks


    CuriousCoder

    Thursday, May 24, 2018 2:26 PM

Answers

  • How do I use that in my current code? 

    Something like this =>

    string sPath = "e:\\test.txt";
    using (FileStream fs = new FileStream(sPath, FileMode.Open, FileAccess.Read, FileShare.None))                
    {                   
        using (var reader = new System.IO.StreamReader(fs))
        {
            string sLine;
            while ((sLine = reader.ReadLine()) != null)                            
            {
                Console.WriteLine(sLine);
            }
        }
    }

    Friday, May 25, 2018 11:28 AM

All replies

  • For example :

    FileStream fs = new FileStream("e:\\test.txt", FileMode.Open, FileAccess.Read, FileShare.None);

    • Proposed as answer by Cor Ligthert Thursday, May 24, 2018 4:32 PM
    Thursday, May 24, 2018 3:51 PM
  • How do I use that in my current code? 

    CuriousCoder

    Friday, May 25, 2018 11:09 AM
  • How do I use that in my current code? 

    Something like this =>

    string sPath = "e:\\test.txt";
    using (FileStream fs = new FileStream(sPath, FileMode.Open, FileAccess.Read, FileShare.None))                
    {                   
        using (var reader = new System.IO.StreamReader(fs))
        {
            string sLine;
            while ((sLine = reader.ReadLine()) != null)                            
            {
                Console.WriteLine(sLine);
            }
        }
    }

    Friday, May 25, 2018 11:28 AM