C# StreamWriter 在单独的类中

标签 c# winforms class methods streamwriter

我在 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) 中,并从我的主窗体中的按钮中调用它。 如果我移动 Button 内的所有内容并将其移动到方法内的 class1,它会声称 Textbox1 不存在,这很明显。

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

最好的问候 数据库

最佳答案

你可以在类里面这样做:

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

关于C# StreamWriter 在单独的类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33496386/

相关文章:

c# - 具有相同名称的非通用类和通用类的不良做法?

全局窗口中无法访问 Javascript ES6 类定义

c# - wcf服务回调异常的处理方法

c# - 判断串口是普通COM还是SPP

c# - 如何使用 SendMessage() 发送鼠标 Action

c# - 将焦点放在按键上

.net - 在 VB.NET 中显示动画 PNG

javascript - css 从一个选项卡应用到另一个选项卡

c# wpf - 多线程

C# 集合合并条目