Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StreamWriter limit in C# in text file

I have an array list which contains 100 lines. When i try to export it into a text file (txt), the output is only 84 lines and it stops in the middle of the 84th line. When I looked at the file size it showed exactly sharp 4.00KB as if there is some kind of a limit to the stream writer. I tried using different parameters etc. but it kept happening.

Here is the code:

FileStream fs = new FileStream(path, FileMode.Create);

        StreamWriter sw = new StreamWriter(fs);
        ArrayList chartList = GetChart(maintNode);

        foreach (var line in chartList)
        {
            sw.WriteLine(line);
        }

        fs.Close();
        Console.WriteLine("Done");

Thanks for the help!

like image 857
Snooker Ball Avatar asked Aug 09 '14 20:08

Snooker Ball


People also ask

What is StreamWriter buffer size?

StreamWriter. BaseStream property is initialized using stream . [Note: The default buffer size can typically be around 4 KB.]

What does StreamWriter mean?

StreamWriter(String, Boolean) Initializes a new instance of the StreamWriter class for the specified file by using the default encoding and buffer size. If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file.

What is StreamReader and StreamWriter?

The StreamReader and StreamWriter classes are used for reading from and writing data to text files. These classes inherit from the abstract base class Stream, which supports reading and writing bytes into a file stream.

What is the difference between FileStream and StreamWriter?

Specifically, a FileStream exists to perform reads and writes to the file system. Most streams are pretty low-level in their usage, and deal with data as bytes. A StreamWriter is a wrapper for a Stream that simplifies using that stream to output plain text.


1 Answers

You need to call StreamWriter.Flush or set StreamWriter.AutoFlush to true. That said, if you use using statment, everything should work fine.

using(StreamWriter sw = new StreamWriter(fs))
{
    ArrayList chartList = GetChart(maintNode);    
    foreach (var line in chartList)
    {
        sw.WriteLine(line);
    }
}

Using statement calls Dispose which will flush the buffer to the FileStream and also closes the file stream. So you don't need to close it manually.

Then I recommend List<T> over ArrayList. ArrayList shouldn't be used, it is not type safe and should be avoided if you're in .Net2.0 or greater.

Also consider using File.WriteAllLines method, so that you don't need these many lines of code. Everything is managed by WriteAllLines method itself.

like image 178
Sriram Sakthivel Avatar answered Sep 28 '22 17:09

Sriram Sakthivel