简体   繁体   English

如何使用Streamwriter将TextBox文本保存到文本文件

[英]How to save TextBox text to text file using streamwriter

Firstoff I have to say that I am new to the c# programming. 首先,我不得不说我是C#编程的新手。 My problem is, that I have a window with a textbox and a button in it and what I am trying to accomplish is to write some text into the textbox and on button click I'd like to save that text into the ukony.txt file. 我的问题是,我有一个带有文本框和按钮的窗口,而我要完成的工作是将一些文本写入文本框,然后单击按钮,我想将该文本保存到ukony.txt文件中。 。 But using the code bellow, after clicking a button nothing happens. 但是使用下面的代码,单击按钮后没有任何反应。

public partial class Window1 : Window {
    public Window1() {
        InitializeComponent();

    }

    private void button_Click(object sender, RoutedEventArgs e) 
        {
        string writerfile = @"D:\Games\ukony.txt";
        Window1 a = new Window1();
        using (StreamWriter writer = new StreamWriter(writerfile)) 
            {
            writer.WriteLine(a.textBlock.Text);
            writer.WriteLine(a.textBlock1.Text);
            }
        }
    }

don't use a new instance of the window. 不要使用窗口的新实例。 Use the current one. 使用当前的。 To access the textblocks of the current instance you should use the this keyword: 要访问当前实例的文本块,您应该使用this关键字:

private void button_Click(object sender, RoutedEventArgs e) 
{
    string writerfile = @"D:\Games\ukony.txt";

    using (StreamWriter writer = new StreamWriter(writerfile)) 
    {
        writer.WriteLine(this.textBlock.Text);
        writer.WriteLine(this.textBlock1.Text);
    }
}

Problem in detail: with this line: 详细问题:使用此行:

Window1 a = new Window1();

you create a new Window with empty controls. 您创建一个带有空控件的新窗口。 These are not the same as the ones you see on the screen and in which you have probably typed in something. 这些与您在屏幕上看到的内容以及您可能在其中键入的内容不同。

The reason for not working is the newly created instance of the Window1 class. 无法工作的原因是Window1类的新创建实例。 which is entirely different from the UI that you are actually seeing. 这与您实际看到的UI完全不同。 So you need not to create an instance at that place, directly use the textBox name to access the text 因此,您无需在该位置创建实例,直接使用textBox名称访问文本

private void button_Click(object sender, RoutedEventArgs e) 
{
    string writerfile = @"D:\Games\ukony.txt";
    using (StreamWriter writer = new StreamWriter(writerfile)) 
    {
        writer.WriteLine(textBlock.Text);
        writer.WriteLine(textBlock1.Text);
    }
}

Why do you want to use a StreamWriter ? 为什么要使用StreamWriter I think it's more easier like this: 我认为这样更容易:

private void button_Click(object sender, RoutedEventArgs e) 
{
    string writerfile = @"D:\Games\ukony.txt";

    System.IO.File.WriteAllText(writerFile, this.textBlock.Text);
    System.IO.File.AppendAllText(writerFile, this.textBlock1.Text);
}

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

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