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:
- When the service writes to the file, an error occurs (the file is occupied by another process)
- How to determine the file encoding of the read file?
- 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.
FileShare.Read- and the service that writes, this does not become bad? Can Write too permit? - Qwertiy ♦