Block reading, opening and editing file

3

How to block a user's opening, reading, and editing of a file during the time the application is running?

An application has a relatively long data collection period. This application reads data in real time. The data read is written to the file every minute. At the end of data collection, I must release the file to the user. I use the code below to save the data every minute. The hidden and read only file attributes do not help me!

string diret=saveFileDialog1.FileName;
Encoding sjisX=Encoding.GetEncoding("Shift_JIS");
StreamWriter arquivo=new StreamWriter(diret,true,sjisX);
arquivo.Write(tb_csv.Text); //salva os dados.
arquivo.Close(); // fecha o arquivo.

//fileProtec.Attributes=FileAttributes.Hidden; permite sua abertura, logo, não serve!
    
asked by anonymous 19.07.2017 / 05:00

1 answer

2

Instead of creating the StreamWriter object with the file path, create a FilesTream and the pass to StreamWriter .

For example:

string diret = saveFileDialog1.FileName;
using (FileStream arquivo =  // Isso é o que realmente abre o arquivo. Não esqueça o using.
        File.Open(diret,
                  FileMode.OpenOrCreate,
                  FileAccess.ReadWrite,
                  FileShare.None)) {

    using (StreamWriter escritor = new StreamWriter(arquivo)) // esse objeto não é o arquivo, é quem escreve nele.
    {
        escritor.BaseStream.Seek(0, SeekOrigin.End); // Posicionamos o cursor de escrita no final do arquivo.

        escritor.Write(tb_csv.Text);
        escritor.flush(); // Caso hajam dados em buffer ainda não escritos, forçamos sua escrita.

        escritor.Close();
    }
}

This blocks reading by other processes because of the signing of the Open method class File . This method can tell the operating system that you do not want to share the file with other processes, through its last parameter. From the official documentation :

  

FileShare.None: Declines sharing of the current file. Any request to open the file (by this process or another) will fail until the file is closed.

    
19.07.2017 / 14:14