繁体   English   中英

C#-Streamwriter类

[英]c# - Streamwriter Class

我试图用StreamWriter类将List<string>写入文件。 当iam将args(在调试模式下)传递给write_lines()函数时,程序将停止,而不会出现任何错误。 也许有人知道我做错了什么

    public class Writer
{
    private StreamWriter the_writer;
    private string PS_filepath;

    public Writer()
    {

    }

    public void write_lines(List<string> thelines, string path)
    {
        this.PS_filepath = path;
        this.the_writer = new StreamWriter(PS_filepath, true);

        foreach(string line in thelines)
        {
            the_writer.WriteLine(line);
        }
    }
}

Path var is C:\\path\\text.xyz

您的编写器是在本地创建的,但从未正确关闭。

没有理由将变量存储在实例中,因此可以将整个方法简单地设置为静态的:

public static void write_lines(List<string> thelines, string path)
{
    //this.PS_filepath = path;
    using (StreamWriter writer = new StreamWriter(path, true))
    {
      foreach(string line in thelines)
      {
          writer.WriteLine(line);
      }
    }
}

using将确保您的文件已关闭(因此已完全写入)。 其他更改只是很小的改进。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM