【问题标题】:stream does not exist in the current context using try [duplicate]使用 try [重复] 在当前上下文中不存在流
【发布时间】:2015-12-07 05:46:53
【问题描述】:

我正在尝试从服务器读取一些数据以获取内置更新功能,但出现编译时错误。有什么办法可以解决这个问题吗?我需要这个来检查用户是否有可用的互联网连接,如果没有则跳过更新检查。 (除非 .Net 4.5 中有更可靠的方法)

WebClient client = new WebClient();
try 
{ 
   Stream stream = client.OpenRead("http://repo.itechy21.com/updatematerial.txt"); 
}
catch (Exception ex)
{ MessageBox.Show(ex.Message); }

StreamReader reader = new StreamReader(stream); // <-- error here
String content = reader.ReadLine();

错误:

当前上下文中不存在流

【问题讨论】:

标签: c# .net webclient filestream


【解决方案1】:

只需在try 块之前声明Stream 变量。否则,其范围仅限于 try 块本身。请记住,变量的范围是声明它的代码块。只需查看围绕变量的最内部的左大括号和右大括号,您就会立即知道在哪里引用该变量是合法的。

Stream stream; // or Stream stream = null;
try
{
    stream = client.OpenRead("http://repo.itechy21.com/updatematerial.txt");
}
// rest of code

【讨论】:

  • 更好地解密Stream stream = null;。在这种情况下,如果流不为空,您可以在 try..catch 块之后检查。
【解决方案2】:

您需要在 try 语句之外声明“Stream stream”,以便在您的 catch 中使用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2018-04-08
    • 1970-01-01
    相关资源
    最近更新 更多