Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 686
Lorenzo Verri Avatar asked Mar 16 '13 18:03

Lorenzo Verri


People also ask

What does FileStream close () do?

Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.


1 Answers

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");
}
like image 83
Davin Tryon Avatar answered Sep 21 '22 09:09

Davin Tryon