Stream Writer没有写入文件,没有异常有file.close();

时间:2015-03-22 12:01:02

标签: c# file-io

我有以下代码: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();
}

正如您所看到的,在方法结束附近有一个关闭的方法。然而,我写的文本文件也没有改变。

2 个答案:

答案 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内。这样,即使您点击“返回”文件,文件也会一直关闭。言。