• Profile
  • Resume
  • Portfolio
  • Blog
Avatar

Nelson Silva

A human. Being. Coffee lover.

Blog

I Write My Thoughts Here

StreamWriter Class in C#

January 12, 2022 C#

In this post, you will learn how to work with the StreamWriter class so that you can use that same knowledge and thus evolve.

  • this class (belonging to System.IO library) aims to implement a writing mode so that characters can be written in a stream (file) according to a specific encoding.
StreamWriter (object).Write() Write all its contents to the file without breaking the line
StreamWriter (object).WriteLine() Write all your content to the file and change the line
StreamWriter (object).Close() Terminate existing link with the given file
  • using guarantees the correct use of the mechanism that frees resources that are not being managed/used.
using System.Collections.Generic;
using System.IO;

namespace Base {
  class StreamWriterClass {
    private StreamWriter writeFile;
    private List<string> countries = new List<string>() {
      "Portugal",
      "Brazil",
      "Spain",
      "France",
      "Italy",
      "Australia",
      "India"
    };

    public void Run() {
      /*
        writeFile = new StreamWriter("File.txt");

        foreach (var country in countries)
          writeFile.WriteLine(country);

        writeFile.Close();
      */

      using (writeFile = new StreamWriter("File.txt")) {
        foreach (var country in countries)
          writeFile.WriteLine(country);
      }
    }
  }
}

Don’t forget to watch the video and you can always read this post in Portuguese.

Happy coding!

Previous Next

Categories

  • Announcements
  • Python
  • C#
  • Java
  • Go

Latest Posts

  • for Loop in Go
    May 5, 2022
  • Switch in Go
    May 4, 2022
  • Comparison Operators in Go
    May 3, 2022
+351913416022
contact@nelsonsilvadev.com
Porto, Portugal
Nelson Silva © 2022 All Rights Reserved