【问题标题】:C# how to clear the streamwriter buffer without writing to a txt file?C#如何在不写入txt文件的情况下清除streamwriter缓冲区?
【发布时间】:2014-02-13 17:58:48
【问题描述】:

我正在 Win7 上开发 C#。

我需要使用 Streamwriter 写入 txt 文件。

   StreamWriter outfile  = new StreamWriter(MY_PATH, true);
   foreach(a line of strings)
   {
       // process the line
        outfile.Write(String.Format(WIDTH + " " + WIDTH, num1Str+"\t", num2Str+"\t"));

   }
   if all elements in line are "0"
      // do not write anything to the file, clear outfile buffer

   // WIDTH are constants. num1Str and num2Str are variables.

如何清除写入流缓冲区的内容?

Flush 不是解决方案,因为如果所有元素都为 0,我不想写入文件。 任何帮助,将不胜感激。

【问题讨论】:

  • 我认为你错过了使用string.Format()的意义
  • 你的forloop是做什么的?看起来它循环写入是为了好玩。您能否使用真实代码,以便我们可以看到什么取决于什么。因为你的“一行字符串”用在了哪里?你聪明吗?在那种情况下,你在哪里使用 char?
  • 好的,那么 foreach 有什么用呢?您是否将相同的内容写了 X 次? num1Str 和 num2Str 是变量吗?它们来自“一行字符串”吗?
  • @Thomas Andreè Lian,num1Str 和 num2Str 来自另一个数据结构。
  • 那么你的 foreach 循环在做什么?

标签: c# io


【解决方案1】:

我相信你正在寻找outfile.Flush();

更新:所以现在问题更清楚了,您不需要StreamWriter,而是想利用MemoryStream 之类的东西。考虑以下 sn-p:

   var writeToDisk = false;
   var outfile  = new MemoryStream();
   foreach(a line of strings)
   {
       // process the line

       // BTW: the `String.Format` you have here is exceptionally confusing
       // and may be attributing to why everything is \0
       outfile.Write(...);

       // set the flag to `true` on some condition to let yourself know
       // you DO want to write
       if (someCondition) { writeToDisk = true; }
   }

   if (writeToDisk)
   {
       var bytes = new byte[outfile.Length];
       outfile.Read(bytes, 0, outfile.Length);
       File.WriteAllBytes(MY_PATH, bytes);
   }

【讨论】:

  • 刷新不是解决方案,因为如果所有元素都为0,我不想写入文件。应该删除缓冲区中的内容。
  • @user2420472:那么您不想使用StreamWriter。您已经将字节流式传输到磁盘。改用MemoryStream,然后如果您想写入磁盘,则利用File.WriteAllBytes 并将MemoryStream 中的字节提供给它。
【解决方案2】:

我认为您想要的是Any 用于检查是否有任何不是“0”,但也使用using 会很好,以便您可以正确处理。

if(someString.Any(a=> a != '0')) //if any elements in line are not '0'
{
    using(StreamWriter outfile  = new StreamWriter(MY_PATH, true))
    {
        foreach(char a in someString)
        {
            outfile.Write(WIDTH + " " + WIDTH, num1Str+"\t", num2Str+"\t");
        }
    }
}

【讨论】:

  • 但答案仍然没有复选标记,讨厌那些他们不接受任何东西的问题。
  • 关于 SO 的问题永远不会“完成”。它们不是“完整的”。它们是不断发展和改进的知识集合。问题作者找到他们的解决方案仅仅是问题旅程的开始。它成为一种规范资源,被许多未来的访问者发现、使用、改进和再次使用,这才是真正的价值所在。
【解决方案3】:

如果行中的所有元素都是“0” // 不向文件写入任何内容,清除 outfile 缓冲区

那你为什么不在写之前检查一下你的行的内容呢?

// process the line
string line = String.Format(WIDTH + " " + WIDTH, num1Str+"\t", num2Str+"\t");
if(!line.Trim().All(c => c == '0'))
     outfile.Write(line);

【讨论】:

  • trim().all() 在这里不起作用,我嵌入了诸如 WIDTH 之类的数字。谢谢
  • 它应该可以工作。如果您的所有数字都是0,它不会将该行写入文件。您的行仍然可以包含零。
  • trim() 仅按空间分区。行中有一些数字如WIDTH,是常数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-15
相关资源
最近更新 更多