Note

Access to this page requires authorization. You can try signing in or .

Access to this page requires authorization. You can try .

FileInfo.CreateText Method

Definition

Namespace:
System.IO
Assemblies:
mscorlib.dll, System.IO.FileSystem.dll
Assemblies:
netstandard.dll, System.Runtime.dll
Assemblies:
netstandard.dll, System.IO.FileSystem.dll
Assemblies:
netstandard.dll, System.IO.FileSystem.dll, System.Runtime.dll
Assembly:
System.IO.FileSystem.dll
Assembly:
mscorlib.dll
Assembly:
netstandard.dll
Source:
FileInfo.cs
Source:
FileInfo.cs
Source:
FileInfo.cs
Source:
FileInfo.cs
Source:
FileInfo.cs

Important

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

Creates a StreamWriter that writes a new text file.

public:
 System::IO::StreamWriter ^ CreateText();
public System.IO.StreamWriter CreateText();
member this.CreateText : unit -> System.IO.StreamWriter
Public Function CreateText () As StreamWriter

Returns

A new StreamWriter.

Exceptions

The file name is a directory.

The disk is read-only.

The caller does not have the required permission.

Examples

The following example demonstrates the CreateText method.

using System;
using System.IO;

class Test
{

 public static void Main()
 {
 string path = @"c:\temp\MyTest.txt";
 FileInfo fi = new FileInfo(path);

 if (!fi.Exists)
 {
 //Create a file to write to.
 using (StreamWriter sw = fi.CreateText())
 {
 sw.WriteLine("Hello");
 sw.WriteLine("And");
 sw.WriteLine("Welcome");
 }
 }

 //Open the file to read from.
 using (StreamReader sr = fi.OpenText())
 {
 string s = "";
 while ((s = sr.ReadLine()) != null)
 {
 Console.WriteLine(s);
 }
 }
 }
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//Hello
//And
//Welcome
Imports System.IO
Imports System.Text

Public Class Test

 Public Shared Sub Main()
 Dim path As String = "c:\MyTest.txt"
 Dim fi As FileInfo = New FileInfo(path)

 If fi.Exists = False Then
 'Create a file to write to.
 Dim sw As StreamWriter = fi.CreateText()
 sw.WriteLine("Hello")
 sw.WriteLine("And")
 sw.WriteLine("Welcome")
 sw.Flush()
 sw.Close()
 End If

 'Open the file to read from.
 Dim sr As StreamReader = fi.OpenText()

 Do While sr.Peek() >= 0
 Console.WriteLine(sr.ReadLine())
 Loop
 sr.Close()
 End Sub
End Class
'This code produces output similar to the following; 
'results may vary based on the computer/file structure/etc.:
'
'Hello
'And
'Welcome

Remarks

By default, full read/write access to new files is granted to all users.

Applies to

See also


Feedback

Was this page helpful?