Search code examples
c#streamwriter

How to save TextBox text to text file using streamwriter


Firstoff I have to say that I am new to the c# programming. 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. 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);
            }
        }
    }

Solution

  • The reason for not working is the newly created instance of the Window1 class. which is entirely different from the UI that you are actually seeing. So you need not to create an instance at that place, directly use the textBox name to access the text

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