Eric J.
Eric J.

Reputation: 150108

StreamWriter Creates Zero-Byte File

I have a Task that reads strings from a blocking collection and is supposed to write them out to a file. Trouble is, while the file is created, the size of the file is 0 bytes after the task completes.

While debugging, I see that non-empty lines are retrieved from the blocking collection, and the stream writer is wrapped in a using block.

For debugging I threw in a flush that should not be required and write the lines to the console. There are 100 non-empty lines of text read from the blocking collection.

// Stuff is placed in writeQueue from a different task  
BlockingCollection<string> writeQueue = new BlockingCollection<string>();

Task writer = Task.Factory.StartNew(() => 
{
    try
    {
        while (true)
        {
            using (FileStream fsOut = new FileStream(destinationPath, FileMode.Create, FileAccess.Write))
            using (BufferedStream bsOut = new BufferedStream(fsOut))
            using (StreamWriter sw = new StreamWriter(bsOut))
            {
                string line = writeQueue.Take();
                Console.WriteLine(line); // Stuff is written to the console
                sw.WriteLine(line);
                sw.Flush(); // Just in case, makes no difference
            }
        }
    }
    catch (InvalidOperationException)
    {
        // We're done.
    }
});

Stepping through in the debugger, I see that the program terminates in an orderly manner. There are no unhandled exceptions.

What might be going wrong here?

Upvotes: 1

Views: 2531

Answers (1)

Maur&#237;cio Linhares
Maur&#237;cio Linhares

Reputation: 40333

You are re-creating the file on every run of the loop. Change the FileMode.Create to FileMode.Append and it will keep the previous values you wrote on it.

Also, using exceptions to detect that you should stop is a really bad practice, if this a consumer-producer solution, you can easily do better by having the producer setting a thread safe flag variable signaling it has finished the work and will not produce anything else.

Upvotes: 2

Related Questions