简体   繁体   中英

StreamWriter not flushing

I want to write a file of about 10 million rows. I'm using StreamWriter with a using statement, however it seems that the StreamWriter is not flushing. Here is my code:

public void ExportRecords(IEnumerable<Record> records, string path)
    {
        using(TextWriter writer = new StreamWriter(path))
        {
            writer.WriteLine("header");

            foreach(var record in records)
            {
                string line = "";
                //Fill line with record properties
                writer.WriteLine(line);
            }
        }
    }

At a certain line the StreamWriter doesn't add any rows. So where is the issue?

EDIT

As mentioned is the comments the code is run async.

Here is how it is:

Task.Run(() =>
{
    if (!String.IsNullOrEmpty(folderPath))
    {
        var records = _generator.GenerateData();

        _dataService.ExportRecords(records, $"{folderPath}/RECORDS.csv");
        //Just a message box
        _reporter.ReportMessage($"Generation and exportation finished");
    }
    else
    {
        IsGenerating = false;
        _reporter.ReportMessage("No output file was created");
    }

});

So I did put a breaking point to check if the method starts executing, and it does. I'm just indicating the the code is not stuck in generation method.

Change temporarily the type of your application to Console Application (if it is Windows Application), and add some Console.WriteLine at strategic points so that you have some feedback about the progress of the procedure. Even better you could add logging to your application, using a library like log4net or Serilog . It will be useful in the production phase of your application too, not only in the development/debugging phase.

如果您在操作中间需要它,则必须在某个时候手动调用Flush() ,否则流只会在语句结束时被清除,当它被释放时。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM