使用 try 在当前上下文中不存在流
stream does not exist in the current context using try
我正在尝试从服务器读取一些数据以获得内置更新功能,但出现编译时错误。有什么办法可以解决这个问题吗?我需要这个来检查用户是否有可用的互联网连接,如果没有则跳过更新检查。 (除非.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();
错误:
stream does not exist in the current context
只需在 try
块之前声明 Stream
变量。否则它的范围仅限于 try
块本身。请记住,变量的范围是声明它的代码块。只需查看围绕变量的最内层左大括号和右大括号,您就会立即知道在何处引用该变量是合法的。
Stream stream; // or Stream stream = null;
try
{
stream = client.OpenRead("http://repo.itechy21.com/updatematerial.txt");
}
// rest of code
您需要在 try 语句之外声明 "Stream stream" 才能在 catch 中使用它。
我正在尝试从服务器读取一些数据以获得内置更新功能,但出现编译时错误。有什么办法可以解决这个问题吗?我需要这个来检查用户是否有可用的互联网连接,如果没有则跳过更新检查。 (除非.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();
错误:
stream does not exist in the current context
只需在 try
块之前声明 Stream
变量。否则它的范围仅限于 try
块本身。请记住,变量的范围是声明它的代码块。只需查看围绕变量的最内层左大括号和右大括号,您就会立即知道在何处引用该变量是合法的。
Stream stream; // or Stream stream = null;
try
{
stream = client.OpenRead("http://repo.itechy21.com/updatematerial.txt");
}
// rest of code
您需要在 try 语句之外声明 "Stream stream" 才能在 catch 中使用它。