Lock reading, opening and editing file

Asked

Viewed 270 times

3

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 data read is recorded in file every minute. At the end of the data collection, I must release the file to the user. Use the code below to save the data every minute. The file attributes Hidden and read only 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!

1 answer

2


Instead of creating the object StreamWriter with the file path, create a FilesTream and the pass 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 Open method of the File class. This method can inform the operating system that you do not want to share the file with other processes, through its last parameter. Of official documentation:

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

  • But when you give this writer command. Close(); releases the file ?

  • But, when you give this writer command. Close(); releases the file ? Every minute, will the app open the file, save and close? With the code I currently use; in the save interval the file can be opened. I need the file to remain closed until the end of the data collection and when finished release the file. Another thing, I need a contingency plan. If the program crashes or if the computer is disconnected from power how to access this file?

  • @silviopontes yes, when using the method Close the file is released. I think I understand what you want now. you will never get it if you keep working with files this way. One suggestion is to write the data in a database and generate the file only at the end of the data collection.

  • I am doing this, but if the computer crashes or power goes out I lose the data.

  • @silviopontes with a database this would not happen.

  • Renan, how to use this solution you say of database? Something else; if the machine crashes how I recover the data and convert to csv?

  • @silviopontes this is too big a subject for comments, so I’ll just say that you should use Mysql or Postgre (both free) or MSSQL (the version Express is free). If you need to worry about crashing machines then it has already gotten bad - your application should be in the cloud if it is so sensitive - and to convert to CSV you use the same program with which you collect data (the conversion is on your own).

  • Grateful, really helped a lot.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.