0

How to lock a csv file with C#? I have almost the same need for file protection from this link: How to lock a file with C#? What is different?

        Encoding sjisX2=Encoding.GetEncoding("Shift_JIS");
        StreamWriter arquivo2=new StreamWriter(saveNameTemporaryFull,true,sjisX2);
        arquivo2.Write(tb_csvFull.Text);
        arquivo2.Close();
       //fileProtec.Attributes=FileAttributes.Hidden;

I need to lock the file so it will not open in the period the application is collecting data and saving every minute. Read Only and Hidden does not work, since the user can open the file in excel.

Matt Ellen
  • 11,268
  • 4
  • 68
  • 90
silvio pontes
  • 25
  • 1
  • 7
  • Please refer to this link. It's working for all type of file [enter link description here](https://stackoverflow.com/questions/5888123/how-to-put-a-lock-on-a-file-in-a-multi-user-environment) – Naveen Ganeshe Jul 18 '17 at 10:36
  • 3
    Specify `FileShare.None`, just like the linked answer says? – Alex K. Jul 18 '17 at 10:36

1 Answers1

0

Try this:

using(FileStream fileStream = new FileStream(
     saveNameTemporaryFull, FileMode.OpenOrCreate, 
     FileAccess.ReadWrite, FileShare.None))
     {
         StreamWriter arquivo2 = new StreamWriter(fileStream, true,sjisX2);
         arquivo2.Write(tb_csvFull.Text);
         arquivo2.Close();
     }

Don't forget to close() fileStream;

orgen
  • 170
  • 1
  • 11
  • 1
    Closing it is unnecessary if it's in a using statement. – mason Jul 18 '17 at 13:20
  • The VS marks this " new StreamWriter(fileStream1,true);" with a red line and shows this error message. Error: The best overload method match for 'System.IO.StreamWriter(System.IO.Stream, System.Text.Encoding, int)' has some invalid arguments – silvio pontes Jul 19 '17 at 01:39
  • The VS marks this " new StreamWriter(fileStream1,true, sjisX2);" with a red line and shows this error message. Error: The best overload method match for 'System.IO.StreamWriter(System.IO.Stream, System.Text.Encoding, int)' has some invalid arguments – silvio pontes Jul 19 '17 at 01:46
  • It should be the encrypting StreamWriter from your example above. Hope this is possible. I cannot test it here. – orgen Jul 19 '17 at 05:12