Create text file and write string to it in CSharp

Description

The following code shows how to create text file and write string to it.

Example


         //from   w  w w . ja  va2  s. c o m

using System;
using System.IO;

class MainClass
{
  static void Main(string[] args)
  {
    StreamWriter MyStream = null;
    string MyString = "Hello World";

    try
    {
      MyStream = File.CreateText("MyFile.txt");
      MyStream.Write(MyString);
    }
    catch (IOException e)
    {
      Console.WriteLine(e);
    }
    catch (Exception e)
    {
      Console.WriteLine(e);
    }
    finally
    {
      if (MyStream != null)
        MyStream.Close();
    }
  }
}




















Home »
  C# Tutorial »
    IO »




File Attribute
File Security
Directory Attribute
Directory Recursive
Binary File
Text Field
Buffered IO
Create Copy Delete Move
CSV
Drive
File System Watcher
Isolated Storage
MemoryStream
Serialize
Zip