Reputation: 313
I have this TextWriter
public static string txt = "./Logs.txt";
public static TextWriter Logs = File.CreateText(txt);
I want to do something like this
textBox1.Text = Logs.ToString();
or like this
Logs.Flush();
textBox1.Text = "";
File.WriteAllText(txt, textBox1.Text);
I tried this too
public class ControlWriter : TextWriter
{
private Control textbox;
public ControlWriter(Control textbox)
{
this.textbox = textbox;
}
public override void Write(char value)
{
textbox.Text += value;
}
public override void Write(string value)
{
textbox.Text += value;
}
public override Encoding Encoding
{
get { return Encoding.ASCII; }
}
}
//in the Form_Load
TextWriter TW = new ControlWriter(textBox1);
It works but if the application starts to write continuously, the application will freeze....
Upvotes: 1
Views: 2181
Reputation: 313
I found the solution, here is the code I used
Logs.Flush();
using (FileStream Steam = File.Open(txt, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (StreamReader Reader = new StreamReader(Steam))
{
while (!Reader.EndOfStream)
{
textBox1.Text = Reader.ReadToEnd();
break;
}
}
}
Upvotes: 1
Reputation: 50
It seems like you want to read the data, but the question doesn't clearly describes it so I'll assume it.
If so, you can use TextReader
...
Edit
TextWriter Logs = File.CreateText(txt);
Logs.Close();
TextReader logs = File.OpenText(txt);
String data = logs.ReadToEnd();
logs.Close();
The above code works, you have to close the file which was opened for it to be used in any other process.
However, I would suggest using File
to create and read the file. It's easy, you don't have to close the file after creation or reading, and it's short.
Example:
//To create file, where *txt* is your path.
File.WriteAllText(txt, "Whatever you want in file.");
//To read your file, where *txt* is your path.
String data = File.ReadAllText(txt)
Upvotes: 1