我在 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/