TextWriter 到 TextBox

TextWriter to TextBox

我有这个TextWriter

    public static string txt = "./Logs.txt";
    public static TextWriter Logs = File.CreateText(txt);

我想做这样的事情

    textBox1.Text = Logs.ToString();

或者像这样

    Logs.Flush();
    textBox1.Text = "";
    File.WriteAllText(txt, textBox1.Text);

我也试过了

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);

可以,但如果应用程序开始连续写入,应用程序将冻结....

看来你是想看数据,但是问题描述的不是很清楚,所以我就假设了。

如果是这样,您可以使用 TextReader ...

For how to use it, see this.

For Documentation

编辑

TextWriter Logs = File.CreateText(txt);
Logs.Close();
TextReader logs = File.OpenText(txt);
String data = logs.ReadToEnd();
logs.Close();

以上代码有效,您必须关闭打开的文件才能在任何其他进程中使用它。

不过,我建议使用 File 来创建和读取文件。很简单,创建或读取后不必关闭文件,而且很短。

示例:

//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)

我找到了解决方案,这是我使用的代码

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