我在form1中有一个文本框和一个按钮,当我在文本框中编写内容时,可以使用我的按钮将其保存到计算机上的文件中。这放在我的按钮里面

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


但是无论如何,我想将所有与streamWriter有关的东西移到他们自己的类(Class1)中,并从我的主窗体中的按钮中调用它。
如果我将所有内容移动到insde按钮中并将其移动到方法内部的class1上,则它声称Textbox1不存在,这很明显。

关于我应阅读的更多内容,您有任何提示或链接吗?

最好的祝福
D B

最佳答案

您可以在这样的课程中进行操作:

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


并在您的按钮事件中:

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

10-08 06:00
查看更多