-2

I am attempting to read some data off of a server for a built in update function and I am getting a compile time error. Is there any way I can get around this? I need this to check if the user has a working internet connection and if not skip the update check. (Unless there are more reliable ways in .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();

Error:

stream does not exist in the current context

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
iTechy
  • 283
  • 1
  • 3
  • 18
  • [How to use downvotes](http://stackoverflow.com/help/privileges/vote-down) Would you care to awnser why? – iTechy Sep 10 '15 at 19:50
  • iTechy, that topic [When justiffiable to downvote](http://meta.stackoverflow.com/questions/252677/when-is-it-justifiable-to-downvote-a-question) goes into more details, along with discussions to require comments on downvotes - http://meta.stackoverflow.com/questions/250177/require-a-comment-explaining-the-reason-for-the-first-downvote-on-a-question. TL;DR - no research shown => negative votes. – Alexei Levenkov Sep 10 '15 at 19:56
  • Thanks for expanding upon that :) – iTechy Sep 10 '15 at 20:10

2 Answers2

4

Just declare the Stream variable before the try block. Otherwise its scope is limited to the try block itself. Remember that the scope of a variable is the block of code where it is declared. Just look at the most-inner opening and closing braces surrounding the variable and you'll immediately know where it's legal to refer to that variable.

Stream stream; // or Stream stream = null;
try
{
    stream = client.OpenRead("http://repo.itechy21.com/updatematerial.txt");
}
// rest of code
Kapol
  • 6,383
  • 3
  • 21
  • 46
  • Better declate `Stream stream = null;`. In that case you can check after try..catch block if stream is not null. – Epsil0neR Sep 10 '15 at 19:48
0

you need to declare "Stream stream" outside of your try statement in order to use it within your catch.