简体   繁体   中英

Stream Writer not writing to file, no exception have file.close();

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.

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...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM