C#如何在不写入txt文件的情况下清除Streamwriter缓冲区? [英] C# how to clear the streamwriter buffer without writing to a txt file?

查看:366
本文介绍了C#如何在不写入txt文件的情况下清除Streamwriter缓冲区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Win7上使用C#.

I am working on C# on Win7.

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

I need to use Streamwriter to write to a txt file.

   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.

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

How to clear the contents written in the stream buffer ?

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

Flush is not a solution because I do not want to write the file if all elements are 0. Any help would be appreciated.

推荐答案

我认为您想要的是Any来检查是否不是"0",但也可以使用using,这样您就可以正确处理.

I think what you want is the Any for checking if any is not "0", but also using using would be nice so that you can dispose properly.

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");
        }
    }
}

这篇关于C#如何在不写入txt文件的情况下清除Streamwriter缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆