System.IO.StreamWriter不会为整个for循环编写

编程入门 行业动态 更新时间:2024-10-26 16:28:53
本文介绍了System.IO.StreamWriter不会为整个for循环编写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试将一长串数字写入C#中的文件,但是它在列表结尾之前一直停下来.例如下面的代码:

I am trying to write a long list of numbers to a file in C# but it keeps stopping before the end of the list. For example the following code:

System.IO.StreamWriter file = new System.IO.StreamWriter("D:\\test.txt"); for (int i = 0; i < 500; i++) { file.WriteLine(i); }

给我留下一个列出数字0至431的文本文件.将500更改为1000会使我获得0到840的信息.在循环结束之前,它似乎总是停止写入.成功将数字输出到控制台以及文件会在控制台中显示完整列表,但不会显示文件.

Leaves me with a text file listing the numbers 0 to 431. Changing 500 to 1000 gets me 0 to 840. It just always seems to stop writing before the loop is finished. Outputing the numbers to console as well as file successfully gives the full list in the console, but not the file.

推荐答案

您需要在退出程序之前关闭编写器,以确保所有缓冲的输出都已写入文件.

You need to close the writer before exiting your program, to make sure that all the buffered output gets written to the file.

一种非常方便的方法是使用 使用 语句,该语句确保您的循环完成后, StreamWriter 被关闭:

A one very convenient way of doing it is with the using statement, which ensures that the StreamWriter gets closed once your loop is done with it:

using (System.IO.StreamWriter file = new System.IO.StreamWriter("D:\\test.txt")) { for (int i = 0; i < 500; i++) { file.WriteLine(i); } }

更多推荐

System.IO.StreamWriter不会为整个for循环编写

本文发布于:2023-11-15 19:51:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1597458.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:会为   System   IO   StreamWriter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!