如何创建';全球streamwriter';在c#winforms中
有人能告诉我如何制作一个全球如何创建';全球streamwriter';在c#winforms中,c#,winforms,C#,Winforms,有人能告诉我如何制作一个全球Streamwriter 我的代码: try { // Try to create the StreamWriter StreamWriter File1 = new StreamWriter(newPath); } catch (IOException) { /* Catch System.IO.IOException was unhandled Message=The process cannot access the fil
Streamwriter
我的代码:
try
{
// Try to create the StreamWriter
StreamWriter File1 = new StreamWriter(newPath);
}
catch (IOException)
{
/* Catch System.IO.IOException was unhandled
Message=The process cannot access the file 'C:\Users\Dilan V 8
Desktop\TextFile1.txt' because it is being used by another process.
*/
File1.Write(textBox1.Text);
File1.Close();
throw;
}
我得到的错误是当前上下文中不存在名称“File1”将变量声明移到try/catch之外,将使其同时存在于try和catch的作用域(上下文)内 但是,我不确定您试图完成什么,因为在这种情况下,您进入catch的唯一方法是如果您未能尝试打开文件,并且在这种情况下,您无法在catch中写入该文件
StreamWriter file1 = null; // declare outside try/catch
try
{
file1 = new StreamWriter(newPath);
}
catch (IOException)
{
if(file1 != null){
file1.Write(textBox1.Text);
file1.Close();
}
throw;
}
移动变量以便在try-catch之前声明它并不会使它成为全局变量,它只是使它在您所在的方法中的剩余代码的整个范围内存在
如果您想在类中创建一个全局变量,您可以这样做
public class MyClass{
public string _ClassGlobalVariable;
public void MethodToWorkIn(){
// this method knows about _ClassGlobalVariable and can work with it
_ClassGlobalVariable = "a string";
}
}
在C#中,事物在一个范围内声明,并且仅在该范围内可用
您在try范围内声明变量File1,虽然它的初始化位置正确(它可能引发异常),但您需要事先声明它,以便在外部范围内(try和catch都在该范围内)都可以使用它
StreamWriter File1 = null;
try
{
// Try to create the StreamWriter
File1 = new StreamWriter(newPath);
}
catch (IOException)
{
/* Catch System.IO.IOException was unhandled
Message=The process cannot access the file 'C:\Users\Dilan V 8
*/ Desktop\TextFile1.txt' because it is being used by another process.
File1.Write(textBox1.Text);
File1.Close();
throw;
}
然而,这仍然是一种错误的方法,因为您在尝试中所做的唯一事情就是实例化一个新的StreamWriter。如果你最终被捕获,这意味着这失败了,如果它失败了,你就不应该再接触对象,因为它没有正确构造(你既不向它写入也不关闭它,你根本不能向它写入,它不工作)
基本上,你在代码中所做的是说“试着启动汽车引擎,如果它失败了,无论如何都要开始踩油门”