user1559904
user1559904

Reputation: 15

c# - Streamwriter Class

Iam trying to write a List<string> to a file with the StreamWriterclass. When iam passing the args (in debugging mode) to the write_lines() function the program stops without any error. Maybe someone has a clue what iam doing wrong

    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

Upvotes: 0

Views: 327

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273844

Your writer is created locally but never properly closed.

There is no reason to store the variable in the instance and because of that the whole method can simply be made static:

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);
      }
    }
}

The using will ensure your file is closed (and therefore written completely). The other changes are just small improvements.

Upvotes: 3

Related Questions