Daniel Bergstrom
Daniel Bergstrom

Reputation: 55

C# StreamWriter in separate class

I have a Textbox and a button in form1, and when i write in the textbox i can save it to a file on the computer using my button. This is placed inside my button

    public void button1_Click(object sender, EventArgs e)
    {
        string FileName = "C:\\sample\\sample.txt";
        System.IO.StreamWriter WriteToFile;
        WriteToFile = new System.IO.StreamWriter(FileName);
        WriteToFile.Write(textBox1.Text);
        WriteToFile.Close();
        MessageBox.Show("Succeded, written to file");

But anyway, I want to move everything to do with streamWriter to their own class (Class1) and call it from my main form, inside the button. If i move all the content insde the Button and move it to class1 inside a method, it claims that Textbox1 doesn't exist, obvious.

Do you have any tips or links on what i should read more about?

Best Regards DB

Upvotes: 1

Views: 327

Answers (1)

Racil Hilan
Racil Hilan

Reputation: 25351

You can do it in the class like this:

public class MyClass {
    public static bool WriteToFile(string text){
        string FileName = "C:\\sample\\sample.txt";
        try {
            using(System.IO.StreamWriter WriteToFile = new System.IO.StreamWriter(FileName)){
                WriteToFile.Write(text);
                WriteToFile.Close();
            }
            return true;
        }
        catch {
            return false;
        }
    }
}

And in your button event:

public void button1_Click(object sender, EventArgs e){
    if(MyClass.WriteToFile(textBox1.Text))
        MessageBox.Show("Succeded, written to file");
    else
        MessageBox.Show("Failer, nothing written to file");
}

Upvotes: 3

Related Questions