File.CreateText Method (String)
Creates or opens a file for writing UTF-8 encoded text.
Assembly: mscorlib (in mscorlib.dll)
Parameters
- path
-
Type:
System.String
The file to be opened for writing.
Return Value
Type: System.IO.StreamWriterA StreamWriter that writes to the specified file using UTF-8 encoding.
| Exception | Condition |
|---|---|
| UnauthorizedAccessException | The caller does not have the required permission. |
| ArgumentException | path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars. |
| ArgumentNullException | path is null. |
| PathTooLongException | 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. |
| DirectoryNotFoundException | The specified path is invalid (for example, it is on an unmapped drive). |
| NotSupportedException | 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.
Imports System Imports System.IO Imports System.Text Public Class Test Public Shared Sub Main() Dim path As String = "c:\temp\MyTest.txt" If Not File.Exists(path) Then ' Create a file to write to. Using sw As StreamWriter = File.CreateText(path) sw.WriteLine("Hello") sw.WriteLine("And") sw.WriteLine("Welcome") End Using End If ' Open the file to read from. Using sr As StreamReader = File.OpenText(path) Do While sr.Peek() >= 0 Console.WriteLine(sr.ReadLine()) Loop End Using End Sub End Class
for writing to the specified file. Associated enumeration: FileIOPermissionAccess.Write
Available since 10
.NET Framework
Available since 1.1
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0