StreamWriter追加随机数据

voi*_*oid 3 c# windows streamwriter .net-3.5 windows-server-2008

我看到使用StreamWriter类使用以下代码将额外的数据写入文件时出现奇怪的行为:

public void WriteToCSV(string filename)
{
    StreamWriter streamWriter = null;
    try
    {
        streamWriter = new StreamWriter(filename);
        Log.Info("Writing CSV report header information ... ");
        streamWriter.WriteLine("\"{0}\",\"{1}\",\"{2}\",\"{3}\"", ((int)CSVRecordType.Header).ToString("D2", CultureInfo.CurrentCulture), m_InputFilename, m_LoadStartDate, m_LoadEndDate);

        int recordCount = 0;

        if (SummarySection)
        {
            Log.Info("Writing CSV report summary section ... ");
            foreach (KeyValuePair<KeyValuePair<LoadStatus, string>, CategoryResult> categoryResult in m_DataLoadResult.DataLoadResults)
             {
                streamWriter.WriteLine("\"{0}\",\"{1}\",\"{2}\",\"{3}\"", ((int)CSVRecordType.Summary).ToString("D2", CultureInfo.CurrentCulture), categoryResult.Value.StatusString, categoryResult.Value.Count.ToString(CultureInfo.CurrentCulture), categoryResult.Value.Category);
                recordCount++;
             }
        }

        Log.Info("Writing CSV report cases section ... ");
        foreach (KeyValuePair<KeyValuePair<LoadStatus, string>, CategoryResult> categoryResult in m_DataLoadResult.DataLoadResults)
        {
            foreach (CaseLoadResult result in categoryResult.Value.CaseLoadResults)
            {
                if ((LoadStatus.Success == result.Status && SuccessCases) ||
                    (LoadStatus.Warnings == result.Status && WarningCases) ||
                    (LoadStatus.Failure == result.Status && FailureCases) ||
                    (LoadStatus.NotProcessed == result.Status && NotProcessedCases))
                {
                    streamWriter.Write("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\"", ((int)CSVRecordType.Result).ToString("D2", CultureInfo.CurrentCulture), result.Status, result.UniqueId, result.Category, result.ClassicReference);
                    if (RawResponse)
                    {
                        streamWriter.Write(",\"{0}\"", result.ResponseXml);
                    }
                    streamWriter.WriteLine();
                    recordCount++;
                }
            }
        }

        streamWriter.WriteLine("\"{0}\",\"{1}\"", ((int)CSVRecordType.Count).ToString("D2", CultureInfo.CurrentCulture), recordCount);

        Log.Info("CSV report written to '{0}'", fileName);
    }
    catch (IOException execption)
    {
        string errorMessage = string.Format(CultureInfo.CurrentCulture, "Unable to write XML report to '{0}'", fileName);
        Log.Error(errorMessage);
        Log.Error(exception.Message);
        throw new MyException(errorMessage, exception);
    }
    finally
    {
        if (null != streamWriter)
        {
            streamWriter.Close();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

产生的文件在0到N的每一行中包含一组记录,例如:

[Record Zero]
[Record One]
...
[Record N]
Run Code Online (Sandbox Code Playgroud)

但是,生成的文件包含空值或不完整的记录,这些记录来自追加到末尾的文件。例如:

[Record Zero]
[Record One]
...
[Record N]
[Lots of nulls]
Run Code Online (Sandbox Code Playgroud)

要么

[Record Zero]
[Record One]
...
[Record N]
[Half complete records]
Run Code Online (Sandbox Code Playgroud)

这也发生在单独的代码段中,这些代码段也使用StreamWriter类。此外,生成的所有文件的大小都是1024的倍数。我无法在任何其他计算机上重现此行为,并尝试重新创建环境。尽管该方法具有相同的代码,但该应用程序的先前版本并未表现出此行为。

编辑:添加了额外的代码。

Mar*_*ell 5

在流的末尾谈论垃圾时,有两种情况让人想到:

  1. 覆盖时不会截断:如果覆盖文件但写入的数据较少,则必须截断它。打开文件时有一个重载,您也可以使用theStream.SetLength
  2. 写缓冲区填充;特别是,当使用最常见的错误是MemoryStream-你必须要么使用.ToArray()(以获得正确的字节数),使用.GetBuffer() ,但只复制.Length字节的缓冲区出(过去的东西是垃圾)

我猜这里是否适用“ 1”?