Write File From Console input - CSharp File IO

CSharp examples for File IO:Text File

Description

Write File From Console input

Demo Code

using System;// w  ww  . j a  va 2s. co  m
using System.IO;
public class Program
{
   public static void Main(string[] args)
   {
      StreamWriter sw = null;
      string fileName = "";
      while(true)
      {
         try
         {
            Console.Write("Enter filename " + "(Enter blank filename to quit):");
            fileName = Console.ReadLine();
            if (fileName.Length == 0)
            {
               break;
            }
            sw = GetWriterForFile(fileName);
            WriteFileFromConsole(sw);
            sw.Close();
            sw = null;
         }
         catch (IOException ioErr)
         {
            string dir = Directory.GetCurrentDirectory();  // Directory class.
            string path = Path.Combine(dir, fileName); // System.IO.Path class.
            Console.WriteLine("Error on file {0}", path);
            Console.WriteLine(ioErr.Message);
         }
      }
   }
   private static StreamWriter GetWriterForFile(string fileName)
   {
      StreamWriter sw;
      FileStream fs = File.Open(fileName,FileMode.CreateNew,FileAccess.Write);
      sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
      return sw;
   }
   private static void WriteFileFromConsole(StreamWriter sw)
   {
      Console.WriteLine("Enter text; enter blank line to stop");
      while (true)
      {
         string input = Console.ReadLine();
         if (input.Length == 0)
         {
            break;
         }
         sw.WriteLine(input);
      }
   }
}

Result


Related Tutorials