FileStream.WriteLine() is not writing to file
Asked Answered
S

6

8

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.

Sultana answered 16/3, 2013 at 18:16 Comment(4)
First of all, the try/finally blocks are not needed, you can use a using block instead.Lampedusa
you may need to flush the StreamWriter: fw.Flush()Penurious
StreamWriter has a constructor that takes a string, the path to the file, and a bool, set to true to append. It would have helped you to fall in the pit of success.Erroneous
You need to flush AND Close the stream to ensure all data is written. Look here: msdn.microsoft.com/en-us/library/…Purify
P
7

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");
}
Penurious answered 16/3, 2013 at 18:29 Comment(0)
D
6

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

Dextroglucose answered 16/3, 2013 at 18:31 Comment(0)
R
2

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)

Relationship answered 16/3, 2013 at 19:5 Comment(0)
P
1

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");
}
Pelota answered 16/3, 2013 at 18:36 Comment(0)
F
0

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");
}
Frailty answered 16/3, 2013 at 18:36 Comment(0)
M
0

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.

Mayor answered 31/7, 2023 at 12:26 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Constitutional

© 2022 - 2024 — McMap. All rights reserved.