C# how to clear the streamwriter buffer without writing to a txt file?

偶尔善良 提交于 2020-01-25 12:08:07

问题


I am working on C# on Win7.

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 ?

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


回答1:


I believe you're looking for outfile.Flush();.

UPDATE: so now that the question is clearer, you don't want a StreamWriter, you want to leverage something like a MemoryStream instead. Consider the following snippet:

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



回答2:


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



回答3:


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

Then why don't you check your line's content, before you write it ?

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


来源:https://stackoverflow.com/questions/21761947/c-sharp-how-to-clear-the-streamwriter-buffer-without-writing-to-a-txt-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!