写入TXT文件与StreamWriter的和的FileStrea

写入TXT文件与StreamWriter的和的FileStrea

本文介绍了写入TXT文件与StreamWriter的和的FileStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我使用的时候遇到了一些有趣的一个的StreamWriter 与的FileStream 将文本追加到现有文件。 NET 4.5(有没有试过任何旧框架)。我尝试了两种方式,一种努力,一个没有。我想知道这两者之间的区别是什么。 这两种方法都包含在下面的代码在顶部 如果$ b $使用b(File.Create(文件路径))(File.Exists(文件路径)!); 我有一个使用语句创建。因为我通过亲身体验,这是确保应用程序完全关闭该文件的最佳途径找到 非工作方法: 使用(的FileStream F =新的FileStream(文件路径,FileMode.Append,FileAccess.Write))(新的StreamWriter(F))。的WriteLine( somestring); 通过这种方法没有最终被附加到文件。 工作方式: 使用(的FileStream F =新的FileStream(文件路径,FileMode.Append,FileAccess.Write ))使用(StreamWriter的S =新的StreamWriter(F)) s.WriteLine(somestring); 我已经做了一些谷歌搜索,不知道相当该怎么寻找,却没有发现任何信息。那么,为什么是匿名的StreamWriter 失败,其中(非匿名?命名?)的StreamWriter 和 解决方案 这听起来像你没有刷新流。 http://msdn.microsoft.com/en-us/library/system.io .stream.flush.aspx 它看起来像的StreamWriter写入到最终目的地,在这种情况下,该文件之前写入的缓冲器。您还可以设置自动刷新属性,而不必明确刷新它。 的 http://msdn.microsoft.com/en-us/library/system.io.streamwriter.autoflush.aspx 要回答你的问题,当你使用使用块,它调用Dispose上的StreamWriter,它必须依次调用刷新。 I ran into something interesting when using a StreamWriter with a FileStream to append text to an existing file in .NET 4.5 (haven't tried any older frameworks). I tried two ways, one worked and one didn't. I'm wondering what the difference between the two is.Both methods contained the following code at the topif (!File.Exists(filepath)) using (File.Create(filepath));I have the creation in a using statement because I've found through personal experience that it's the best way to ensure that the application fully closes the file.Non-Working Method:using (FileStream f = new FileStream(filepath, FileMode.Append,FileAccess.Write)) (new StreamWriter(f)).WriteLine("somestring");With this method nothing ends up being appended to the file.Working Method:using (FileStream f = new FileStream(filepath, FileMode.Append,FileAccess.Write)) using (StreamWriter s = new StreamWriter(f)) s.WriteLine("somestring");I've done a bit of Googling, without quite knowing what to search for, and haven't found anything informative. So, why is it that the anonymous StreamWriter fails where the (non-anonymous? named?) StreamWriter works? 解决方案 It sounds like you did not flush the stream.http://msdn.microsoft.com/en-us/library/system.io.stream.flush.aspxIt looks like StreamWriter writes to a buffer before writing to the final destination, in this case, the file. You may also be able to set the AutoFlush property and not have to explicitly flush it.http://msdn.microsoft.com/en-us/library/system.io.streamwriter.autoflush.aspxTo answer your question, when you use the "using" block, it calls dispose on the StreamWriter, which must in turn call Flush. 这篇关于写入TXT文件与StreamWriter的和的FileStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-15 10:50