C# File CreateText

Description

File CreateText Creates or opens a file for writing UTF-8 encoded text.

Syntax

File.CreateText has the following syntax.


public static StreamWriter CreateText(
  string path
)

Parameters

File.CreateText has the following parameters.

  • path - The file to be opened for writing.

Returns

File.CreateText method returns A StreamWriter that writes to the specified file using UTF-8 encoding.

Example

The following example creates a file for text writing and reading.


//w w w.  j a va  2 s .  c  om
using System;
using System.IO;

class Test 
{
    public static void Main() 
    {
        string path = @"c:\temp\MyTest.txt";
        if (!File.Exists(path)) 
        {
            using (StreamWriter sw = File.CreateText(path)) 
            {
                sw.WriteLine("Hello");
                sw.WriteLine("And");
                sw.WriteLine("Welcome");
            }  
        }
        using (StreamReader sr = File.OpenText(path)) 
        {
            string s = "";
            while ((s = sr.ReadLine()) != null) 
            {
                Console.WriteLine(s);
            }
        }
    }
}




















Home »
  C# Tutorial »
    System.IO »




BinaryReader
BinaryWriter
Directory
DirectoryInfo
DriveInfo
File
FileInfo
FileStream
MemoryStream
Path
StreamReader
StreamWriter
StringReader
StringWriter