我有以下代码: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();
}
正如您所看到的,在方法结束附近有一个关闭的方法。然而,我写的文本文件也没有改变。
答案 0 :(得分:2)
您应该将StreamWriter
封装在using
构造中:
using(Streamwriter sw = new StreamWriter(...)
{
...
}
这将在所有情况下关闭(并将缓冲区写入文件)(异常,返回等)
在您的代码中,您有很多return
语句,它会使流打开并且缓冲区中已写入的文本永远不会刷新到您的文件中...
答案 1 :(得分:0)
将StreamWriter
放入using语句中:
using (StreamWriter file = new StreamWriter(@"C:\Users\vroy\Desktop\LOG.txt"))
{
file.WriteLine("ENTERING LEFT");
// Rest of code...
}
这实际上将代码放在try / finally
块中,Close / Dispose
位于finally
内。这样,即使您点击“返回”文件,文件也会一直关闭。言。