Lorenzo Verri
Lorenzo Verri

Reputation: 153

FileStream.WriteLine() is not writing to file

I am trying to make a simple software which stores data in a TXT log file. This is my code

FileStream fs = null;
StreamWriter fw = null;
try
{
    fs= new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+"/textme.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
    fw = new StreamWriter(fs);
    fw.Write("sadadasdsadsadsadas");

    for (int i = 0; i < AnimalShelter.AnimalList.Count; i++)
    {
        fw.WriteLine("<chipNr>" + AnimalShelter.AnimalList[i].ChipRegistrationNumber + "<chipNr>");
        Console.WriteLine("<chipNr>" + AnimalShelter.AnimalList[i].ChipRegistrationNumber + "<chipNr>");
    }
}
catch(IOException)
{
    MessageBox.Show("ERROR THROWN");
}
finally
{
    if (fs!= null) fs.Close();
    //  if (fw != null) fw.Close();
}

What I achieved is: the file gets created, but nothing gets written in it. I checked a lot of posts but I could not find any particular help.

Upvotes: 8

Views: 40187

Answers (6)

Vamshi Kancharla
Vamshi Kancharla

Reputation: 1

As codechops mentioned, close() worked for me. I had issue with last write, and using close() of file stream fixed the issue.

Basically data from the stream needs to be flushed onto the file, for write to work properly.

Upvotes: 0

Davin Tryon
Davin Tryon

Reputation: 67296

Adding a call to Flush the stream works. This is because you are wrapping the FileStream. StreamWriter will write to the FileStream, but you need to indicate when to send the Stream to the actual file. Also, you can exchange your try finally with a using:

try
{
    using (var fs = new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+"/textme.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite))
    {
        using (var fw = new StreamWriter(fs))
        {
            fw.Write("sadadasdsadsadsadas");

            for (int i = 0; i < AnimalShelter.AnimalList.Count; i++)
            {
                fw.WriteLine("<chipNr>" + AnimalShelter.AnimalList[i].ChipRegistrationNumber + "<chipNr>");
                Console.WriteLine("<chipNr>" + AnimalShelter.AnimalList[i].ChipRegistrationNumber + "<chipNr>");

            }
            fw.Flush(); // Added
        }
    }
}
catch(IOException)
{
    MessageBox.Show("ERROR THROWN");
}

Upvotes: 7

NSGaga
NSGaga

Reputation: 14302

Always use using (as mentioned already) and you won't run into problems (or have to think about it)...

using (FileStream fs = new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/textme.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite))
using (StreamWriter fw = new StreamWriter(fs))
{
    fw2.Write("sadadasdsadsadsadas");
}  

(also you could have closed the writer instead of filestream which should've worked)

The problem is as I far as I can tell...

FileStream.Close is actually Stream.Close - and that calls Dispose but it ain't virtual, so does some general cleanup.

FileStream.Dispose which is called implicitly when you use using - does specific Flush and then Close/Dispose - so does proper specific cleanup.

You can avoid any of that via using as that is generally recommended pattern (and frankly never got me into any of these)

Upvotes: 2

Steve
Steve

Reputation: 216243

Enclose your StreamWriter in an using block to be sure that everything is correctly closed at the end of the file usage, also I don't think you need to create a FileStream for this to work.

try
{
    string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "textme.txt")
    using(fw = new StreamWriter(fileName, true))
    {
         ......
    }
}
catch(IOException)
{
    MessageBox.Show("ERROR THROWN");
}

Note that the StreamWriter has a constructor that accepts two parameters, the name of the file to create/open and a flag to indicate that the file should be opened in append mode or overwritten See StreamWriter docs

Upvotes: 6

Stefan Over
Stefan Over

Reputation: 6046

Try using this - just replace the array:

try
{
    using (Stream fs = new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/textme.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite))
    {
        using (StreamWriter sw = new StreamWriter(fs))
        {
            int[] test = new int[] { 0, 12, 23, 46 };
            sw.Write("sadadasdsadsadsadas");
            for (int i = 0; i < test.Length; i++)
            {
                sw.WriteLine("<chipNr>" + test[i] + "<chipNr>");
                Console.WriteLine("<chipNr>" + test[i] + "<chipNr>");
            }
            sw.Close();                    
        }
        fs.Close();
    } 

}
catch (IOException)
{
    MessageBox.Show("ERROR THROWN");
}

Upvotes: 0

theMayer
theMayer

Reputation: 16157

Indeed, Flush() is the answer; however, I would use File.WriteAllLines() instead.

try
{
    var fileName = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+"/textme.txt";
    var lines = AnimalShelter.AnimalList.Select(o=> "<chipNr>" + o.ChipRegistrationNumber + "</chipNr>");
    File.WriteAllLines(fileName, lines);
    foreach(var line in lines)
        Console.WriteLine(line);
}
catch(IOException)
{
    MessageBox.Show("ERROR THROWN");
}

Upvotes: 1

Related Questions