Good day.

In order to educate myself, I set myself the task: - there is a text file in which the Windows service writes text lines to this file, so I decided to write an application that reads data from that file synchronously so that it does not block for the service.

Code:

private async void btnOpenFile_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog(); dialog.InitialDirectory = "C:\\"; dialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; dialog.FilterIndex = 2; dialog.RestoreDirectory = true; if (dialog.ShowDialog() == DialogResult.OK) { _fileName = tbFileName.Text = dialog.FileName; try { rtbText.Text = await GetFileText(); } catch (Exception ex) { MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message); } } } async Task<string> GetFileText() { using (FileStream sourceStream = new FileStream(_fileName, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true)) { StringBuilder sb = new StringBuilder(); byte[] buffer = new byte[0x1000]; int numRead; while ((numRead = await sourceStream.ReadAsync(buffer, 0, buffer.Length)) != 0) { //string text = Encoding.ASCII.GetString(buffer, 0, numRead); string text = Encoding.GetEncoding(1251).GetString(buffer, 0, numRead); sb.Append(text); } MessageBox.Show("Loading complete..."); return sb.ToString(); } } 

I encountered the following problems:

  1. When the service writes to the file, an error occurs (the file is occupied by another process)
  2. How to determine the file encoding of the read file?
  3. How to find out the size of the buffer (new byte [0x1000]), which I need for a specific file? After all, the file is constantly increasing in size

Please share your thoughts on this.

Thank.

  • 2
    FileShare.Read - and the service that writes, this does not become bad? Can Write too permit? - Qwertiy ♦

1 answer 1

  1. Your program should be ready for the fact that the file is locked, catch the corresponding exception and try again after a certain period of time.
  2. No For a text file, the encoding must be known in advance. There is no coding information in the text file format, you can only try to guess it with some probability without any guarantees. Agree with the service on what encoding will be written to the file.
  3. The easiest way to read the file is via ReadAllText , and not bother with manual control of the buffers. Reading into a buffer in advance of a given size can lead to a “splitting” of a unicode character, for example. So do not make yourself difficult.
  • 2. What about BOM? - Qwertiy ♦
  • @Qwertiy: BOM, it seems, is only in Unicode, and, it seems, only Microsoft. Well, it is not required. - VladD