StreamWriter附加随机数据

我看到奇怪的行为使用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(); } } } 

生成的文件包含每行0到N的一组logging,例如:

 [Record Zero] [Record One] ... [Record N] 

然而,所产生的文件或者包含空值或者不完整的logging,从进一步追加到最后的文件。 例如:

 [Record Zero] [Record One] ... [Record N] [Lots of nulls] 

要么

 [Record Zero] [Record One] ... [Record N] [Half complete records] 

这也发生在也使用StreamWriter类的单独代码片段中。 此外,生成的文件都有1024的倍数的大小。我已经无法在任何其他机器上重现此行为,并尝试重新创build环境。 尽pipe对于所讨论的方法具有相同的代码,但该应用程序的先前版本没有performance出这种行为。

编辑:添加额外的代码。

在流末尾谈到垃圾时,有两种情况需要思考:

  1. 覆盖时不会截断:如果覆盖文件但写入的数据较少,则必须截断它。 打开文件时有一个重载操作,或者您可以使用theStream.SetLength
  2. 写入缓冲区填充; 特别是最常见的错误是使用MemoryStream – 您必须使用.ToArray() (以获取正确的字节数), 或者使用.GetBuffer() 只能从缓冲区中复制.Length个字节是垃圾)

我猜“1”适用于这里?