如何创建';全球流媒体作家';在c#winforms中

本文关键字:作家 流媒体 c#winforms 创建 何创建 | 更新日期: 2023-09-27 18:20:47

有人能告诉我们如何制作全局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 的错误

如何创建';全球流媒体作家';在c#winforms中

通过将变量的声明移动到try/catch之外,您将使其同时存在于try和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。如果你最终陷入困境,那就意味着失败了,如果失败了,你就不应该再碰这个对象了,因为它没有正确构造(你既不写也不关,你根本无法写,它不起作用)。

基本上,你在代码中所做的是说"试着启动汽车发动机,如果它失败了,无论如何都要启动加速器"。