繁体   English   中英

如何在c#winforms中创建“全局编写器”

[英]How can I create a 'global streamwriter' in 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 file 'C:\Users\Dilan V 8
       Desktop\TextFile1.txt' because it is being used by another process.
    */
    File1.Write(textBox1.Text);
    File1.Close();
    throw;
}

我得到的错误The name 'File1' does not exist in the current context

通过在try / catch之外移动变量的声明,您将使它存在于try和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。 如果你最终陷入了捕获,这意味着失败了,如果它失败了你就不应再触摸该对象,因为它没有正确构造(你不写它也不关闭它,你根本不能写它,它没有用)。

基本上你在代码中所做的就是“尝试启动汽车引擎,如果失败了,无论如何都要开始点击加速器”。

暂无
暂无

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

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