c# - 字符串列表不会完全写入文本文件

标签 c# .net stream

我正在尝试从一个文本文件读取并写入另一个文本文件。我读取的文件有 2023 行,而我正在写入的文件只有 2008 行。我无法弄清楚另一条线发生了什么......我在某个地方丢失了它们。我做错了什么?

谢谢!

这是我的 C# 代码。

     static void Main(string[] args)
    {
        StreamWriter writer = new StreamWriter("C:/Users/Rafael/desktop/newfile.txt");
        StreamReader reader = new StreamReader("C:/Users/Rafael/desktop/new1.txt");//, System.Text.Encoding.GetEncoding("ISO-8859-1"));
        string line;
        while ((line = reader.ReadLine()) != null)
        {

            writer.WriteLine(line);
        }

    }

最佳答案

在任何时候您都不会关闭 streamwriter - 因此它可能不会写入文件。您可以通过在循环之后调用 Close() 来对此进行测试,或者如果您尚未完成文件处理,则可以使用 Flush()。

如果有选择,我会重写代码以使用 Using{} block ,当流超出范围时调用 Dispose() 自动关闭流。

关于c# - 字符串列表不会完全写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7054885/

相关文章:

c# - 我应该使用回调还是引入公共(public)字段来帮助进行单元测试?

.net - 在 .NET 中通过 Process.Start 生成的进程会挂起线程

.net - 在 Delphi 程序中托管 .NET 运行时

c# - WPF TreeView : Why does virtualizing break BringIntoView()?

linux - 如何根据正则表达式模式将流拆分为 stdout+stderr?

java - 字节流上的困惑

Delphi and HDD I/O Quoting , Resource Pre-Caching , Read/Write/seek 参数限制

c# - 如何从源代码 View (aspx) 在 C# 中为来自按钮的事件添加事件处理程序

c# - 无法使 MSMQ WCF 窗口服务运行

c#, Autocad, 显示填充的属性