TextWriter到TextBox

时间:2017-06-11 23:52:53

标签: c# winforms textbox textwriter

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

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

2 个答案:

答案 0 :(得分:1)

好像你想要读取数据,但问题没有清楚地描述它,所以我会假设它。

如果是这样,您可以使用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)

答案 1 :(得分:1)

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

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