简体   繁体   English

TextWriter到TextBox

[英]TextWriter to TextBox

I have this TextWriter 我有这个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.... 它可以工作,但是如果应用程序开始连续写入,则该应用程序将冻结。

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

For how to use it, see this. 有关如何使用它,请参见此。

For Documentation 对于文档

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. 但是,我建议使用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)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM