Reputation: 93
I have the following code: http://pastebin.com/HSjspbek
if (direction == "left" && mazearray[xIndex - 1, yIndex].canPass == false && x <= (xIndex * 18) + 3)
{
System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\vroy\Desktop\LOG.txt");
file.WriteLine("ENTERING LEFT");
file.WriteLine(x + " , " + y);
if (PacMan.yIndex > yIndex)
{
file.WriteLine("yIndex more");
}
if (PacMan.yIndex < yIndex)
{
file.WriteLine("yIndex less");
}
if (PacMan.xIndex == xIndex)
{
file.WriteLine("xIndex same");
}
file.WriteLine("METHOD CALL ENDED");
if (PacMan.yIndex > yIndex && mazearray[xIndex, yIndex + 1].canPass == true)
{
direction = "down";
Console.WriteLine("CHOICE DOWN");
return;
}
if (PacMan.yIndex < yIndex && mazearray[xIndex, yIndex].canPass == true && y <= (yIndex * 18) + 3)
{
file.WriteLine("ENTERING UP");
direction = "up";
return;
}
if (PacMan.xIndex == xIndex)
{
if (mazearray[xIndex, yIndex + 1].canPass == true)
{
direction = "down";
}
else
{
direction = "up";
}
}
file.Close();
}
As you can see there is a close method for the streamwriter object near the end of the method. Yet the text file I am writing too does not change.
Upvotes: 0
Views: 450
Reputation: 5445
Put StreamWriter
in a using statement:
using (StreamWriter file = new StreamWriter(@"C:\Users\vroy\Desktop\LOG.txt"))
{
file.WriteLine("ENTERING LEFT");
// Rest of code...
}
This essentially puts the code in a try / finally
block with the Close / Dispose
inside the finally
. This way the file always gets closed even when you hit a 'return' statement.
Upvotes: 0
Reputation: 9772
You should encapsulate your StreamWriter
in a using
construct:
using(Streamwriter sw = new StreamWriter(...)
{
...
}
This will close (and write buffers to file) in all cases (Exceptions, returns, etc)
In your code you have a lot of return
statement which leave the stream open and the already written text in the buffers is never flushed to your file...
Upvotes: 2