How to declare a public string within a while loop (C#)
I am currently trying to declare a public string within a while loop, as I would like to use it (the string) in other methods
The string in question is "s"
private void CheckLog()
{开发者_开发技巧
bool _found;
while (true)
{
_found = false;
Thread.Sleep(5000);
if (!System.IO.File.Exists("Command.bat")) continue;
using (System.IO.StreamReader sr = System.IO.File.OpenText("Command.bat"))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
if (s.Contains("mp4:production/CATCHUP/"))
{
_found = true;
break;
}
}
}
}
}
you can't declare public
string inside the method.
Try this:
string s = "";
private void CheckLog()
{
bool _found;
while (true)
{
_found = false;
Thread.Sleep(5000);
if (!System.IO.File.Exists("Command.bat")) continue;
using (System.IO.StreamReader sr = System.IO.File.OpenText("Command.bat"))
{
//s = "VALUE";
while ((s = sr.ReadLine()) != null)
{
if (s.Contains("mp4:production/CATCHUP/"))
{
_found = true;
break;
}
}
}
}
}
You should create a global variable and assign that instead for example
public class MyClass
{
public string s;
private void CheckLog() { ... }
}
In any method you might use it remember to check if s.IsNullOrEmpty()
to avoid getting a NullPointerException (also I'm assuming that the string should contain something).
Better pass the string as by-ref argument to function, or return it from the function. Declaring it as member doesn't seem to be a good idea.
public string CheckLog(){}
精彩评论