NullReferenceException with StreamReader.BaseStream.Position/.Length/.CanSeek SOLVED
This piece of code is launched as a Thread and runs at the background of my application. Every 3 seconds it copies a file (because it's locked by another application i can only access it after copying it).
And after that I read all lines that are added to the copied file since the last time I copied it.
Everytime when i close the file I keep track of the position where my cursor was at that moment. Next time I only need to read starting from that position. (I use a static string filepos for this. And at the start of my application its value is set to 0)
All new lines are add to an arraylist to be used in other Threads.
Code:
static private void inputloop()
{
string invoer="";
do
{
FileInfo bestand = new FileInfo(@"out.txt");
if (bestand.Exists)
{
bestand.CopyTo(@"out2.txt",true);
FileInfo bestand2 = new FileInfo(@"out2.txt");
StreamReader sr = new StreamReader(bestand2.OpenText());
sr.BaseStream.Position = filepos;
bool einde = false;
while (!einde)
{
try
{
invoer = sr.ReadLine();
}
catch
{
invoer = null;
}
try
{
if (invoer.Substring(0,1) == "=") //only lines starting with a "="-sign should be added
{
inputList.Add(invoer); //added to the list
}
}
catch{}
if (invoer == null)
{
einde = true;//eof
}
if (sr.BaseStream.CanSeek) // <----------------- error here
{
filepos = sr.BaseStream.Length;
}
sr.Close();
}
}
System.Threading.Thread.Sleep(3000);
}while (true);
}
This looks ok imho. Maybe some things could be done better but it should work, no ? But it doesn't! I get an exception while running it.
Line 106: corresponds to the BaseStream.CanSeek property I'm using. If I leave it away I get the same mistake but for the BaseStream.Length property this time. I also tried with BaseStream.Position. Same error ...
Quote:
Unhandled Exception: System.NullReferenceException: Object reference not set to
an instance of an object.
at gnogo2irc.gnugo2irc.inputloop() in c:\gnogo2irc\gnugo2irc.cs:line 106
Who can help ?