SoFunction
Updated on 2025-03-07

C# How to open files using Streamwriter

This article describes how C# uses Streamwriter to open files. Share it for your reference. The details are as follows:

using System;
using ;
public class KtoD1 {
 public static void Main() {
  string str;
  StreamWriter fstr_out;
  // Open the file directly using StreamWriter.
  try {
   fstr_out = new StreamWriter("");
  }
  catch(IOException exc) {
   ( + "Cannot open file.");
   return ;
  }
  ("Enter text ('stop' to quit).");
  do {
   (": ");
   str = ();
   if(str != "stop") {
    str = str + "\r\n"; // add newline
    try {
     fstr_out.Write(str);
    } catch(IOException exc) {
     ( + "File Error");
     return ;
    }
   }
  } while(str != "stop");
  fstr_out.Close();
 }
}

I hope this article will be helpful to everyone's C# programming.