There is a file where a large number of lines. The output of the file is accomplished by the construction cycle. But due to the fact that the file is large, the action is more than 60 seconds and the exception is caused. How to solve this problem?
streamreader file = new streamreader ("buffer2.txt");
String Line = file.ReadLine ();
While (Line! = NULL)
{
TextBox3.Text + = line + "\ r \ n";
Line = file.ReadLine ();
}
Answer 1, Authority 100%
Public Partial Class Form1: Form
{
// File Startup Flag
Private Bool _isreading;
// Source Tocken Cancellation
Private CancellationTokensource _Tokensource;
Public Form1 ()
{
Initializecomponent ();
}
Private Void Buttonfile_Click (Object Sender, Eventargs E)
{
OpenFileDialog OpenFileDialog = New OpenFileDialog ();
OpenFileDialog.initialDirectory = "D: \\";
OpenFileDialog.Filter = "TXT Files (* .txt) | * .txt";
OpenFileDialog.CheckFileExists = True;
OpenFileDialog.RestOredirectory = True;
if (openfiledialog.showdialog () == dialogresult.ok)
{
textBoxFile.Text = OpenFileDialog.Filename;
buttonreadfile.enabled = true;
}
ELSE.
{
textboxfile.text = string.empty;
buttonreadfile.enabled = false;
}
}
Private Async Void ButtonReadFile_Click (Object Sender, Eventargs E)
{
// If the reading process has already started
if (_isreading)
{
// We cancel reading the file
_Tokensource.cancel ();
Return;
}
// Flag of reading
_isreading = true;
//interface
buttonreadfile.text = "cancel";
buttonfile.enabled = false;
Try.
{
// Preparing current cancellation
_Tokensource = New CancellationTokensource ();
var token = _tokensource.token;
// Run reading, after completion, displays the result
textBoxoutput.Text = await task.run (() = & gt; Readfile (textboxfile.text, token), token);
}
Catch (OperationCanceledException)
{
// Reading was canceled
textboxoutput.text = string.empty;
}
Catch (Exception Ex)
{
MessageBox.Show (EX.Message, "File Reading Error",
MessageBoxButtons.ok, MessageBoxicon.error);
}
Finally
{
_isreading = false;
_Tokensource.dispose ();
buttonreadfile.text = "Read";
buttonfile.Enabled = True;
}
}
Private String Readfile (String File, CancellationToken Token)
{
// to collect read lines
StringBuilder Result = New StringBuilder ();
// To display the progress of the file reader
Action & lt; String & GT; Action = S = & gt; textboxoutput.text = s;
Using (FileStream FS = File.openread (File))
{
Using (StreamReader SR = New StreamReader (FS))
{
String Line = String.Empty;
INT Counter = 1;
While ((Line = Sr.ReadLine ())! = NULL)
{
// throw out the exception in case of cancellation
token.throwifcancellationrequested ();
// add a read string
result.appendline (Line);
// Show the progress of reading
Var Message = $ "Read the file ..., Row: {counter ++}";
If (InvokeRequired)
This.Invoke (Action, Message);
ELSE.
Action (Message);
}
}
}
Return result.tostring ();
}
}