c# – System.IO.StreamWriter不会为整个for循环写入
发布时间:2020-12-15 19:38:20 所属栏目:百科 来源:网络整理
导读:我试图在C#中为一个文件编写一长串数字,但它会在列表结尾之前停止.例如,以下代码: System.IO.StreamWriter file = new System.IO.StreamWriter("D:test.txt"); for (int i = 0; i 500; i++) { file.WriteLine(i); } 给我留下一个列出数字0到431的文本文件
我试图在C#中为一个文件编写一长串数字,但它会在列表结尾之前停止.例如,以下代码:
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.它似乎总是在循环结束之前停止写入.将数字输出到控制台以及文件成功提供控制台中的完整列表,但不是文件. 解决方法
您需要在退出程序之前关闭编写器,以确保将所有缓冲的输出写入文件.
一个非常方便的方法是使用 using (System.IO.StreamWriter file = new System.IO.StreamWriter("D:test.txt")) { for (int i = 0; i < 500; i++) { file.WriteLine(i); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |