繁体   English   中英

C#StreamWriter在单独的类中

[英]C# StreamWriter in separate class

我在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不存在,显而易见。

您对我应该阅读的内容有什么提示或链接吗?

最好的问候DB

你可以在课堂上这样做:

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

暂无
暂无

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

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