c# – Block file reading, opening and editing

Question:

How to block the opening, reading and editing of a file by the user during the period the application is running?

An application has a relatively long data collection period. This application reads data in real time. The read data is written to file every minute. At the end of data collection, I must release the file to the user. Use the code below to save the data every minute. Hidden and read only file attributes don't 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!

Answer:

Instead of creating the StreamWriter object with the file path, create a FilesTream and pass it to the 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 signature of the File class's Open method . This method manages to inform 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 the current file share. Any request to open the file (by this process or otherwise) will fail until the file is closed.

Scroll to Top