Hello to all, I'm trying to use the function below to print strings to a file. When I use Console.Write() or
Console.WriteLine() the output file grows up 3MB or 4MB per seconds, but when I try to use StreamWriter or
File.AppendAllText the output in the way shown below, the file grows up only in 20KB or 30KB per second.

Why the print speed decreases too much when I use StreamWriter instead of Console.WriteLine()?
What method should I use to write to a file maintaining the same speed of Console.WriteLine()?

    public static void PrintFunction()
        //using (StreamWriter writer = File.AppendText(@"C:\OuputFile.txt"))
        using (StreamWriter writer = new StreamWriter(@"C:\OuputFile.txt", true))
            //Console.Write("This is "); // Print speed is about 3MB-4MB per second
            writer.Write("This is "); //Print decreases to 20KB-30KB per second
            //File.AppendAllText(@"C:\OuputFile.txt", "This is "); Print decreases to 20KB-30KB per second

            // SOME CODE
            // SOME CODE

            //Console.WriteLine("the first line"); // Print speed is about 3MB-4MB per second
            writer.WriteLine("the first line"); // Print decreases to 20KB-30KB per second
            //File.AppendAllText(@"C:\OuputFile.txt", "the first line"); // Print decreases to 20KB-30KB per second

Thanks in advance.

Recommended Answers

All 5 Replies

You could try to increase the buffer size(default is 4KB I think) use for instance this constructor

Hi ddanbe,

Thanks for answer. I've followed what you said and I increased the buffer size to 64KB, 128KB and nothing happens, the speed it seems to be the same, the output file still grows up in 30KB or 40KB per second.

I did like this:

    using (StreamWriter writer = new StreamWriter(@"C:\OuputFile.txt", true, Encoding.UTF8, 65536))

Thanks again.

How are you measuring these speeds?

It may be that the StreamWriter class is buffering the output data and won't write the remainder until you close or flush the stream.

Hello cgeier, I only check how increases the output file in windows explorer in size field. One method makes it grows up in KB and the other in MB.

Thanks rubberman and ddanbe again, it seems the issue was that I was open the writer each time I print. Then I defined only once the writer and I close it at the very end and this time it works so nice.

Thanks for your help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.