Search code examples
c#winformstextboxtextwriter

TextWriter to TextBox


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....


Solution

  • 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;
                        }
                    }
                }