CreateText Method

File.CreateText Method (String)


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

Namespace:   System.IO
Assembly:  mscorlib (in mscorlib.dll)

public static StreamWriter CreateText(
	string path


Type: System.String

The file to be opened for writing.

Return Value

Type: System.IO.StreamWriter

A StreamWriter that writes to the specified file using UTF-8 encoding.

Exception Condition

The caller does not have the required permission.


path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.


path is null.


The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.


The specified path is invalid (for example, it is on an unmapped drive).


path is in an invalid format.

This method is equivalent to the StreamWriter(String, Boolean) constructor overload with the append parameter set to false. If the file specified by path does not exist, it is created. If the file does exist, its contents are overwritten. Additional threads are permitted to read the file while it is open.

The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see GetCurrentDirectory.

For a list of common I/O tasks, see Common I/O Tasks.

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

using System;
using System.IO;

class Test 
    public static void Main() 
        string path = @"c:\temp\MyTest.txt";
        if (!File.Exists(path)) 
            // Create a file to write to.
            using (StreamWriter sw = File.CreateText(path)) 

        // Open the file to read from.
        using (StreamReader sr = File.OpenText(path)) 
            string s = "";
            while ((s = sr.ReadLine()) != null) 

for writing to the specified file. Associated enumeration: FileIOPermissionAccess.Write

Universal Windows Platform
Available since 10
.NET Framework
Available since 1.1
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Return to top
© 2015 Microsoft