File: CreateText

CreateText

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



 Public Function CreateText(
	  ByRef Path As String ) As StreamWriter

Parameters

Path
[ByRef] String. The file to be opened for writing.

Return Values

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

Remarks

This method is equivalent to the NewStreamWriter(String) 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.

Exceptions

ExceptionCondition
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 GetInvalidPathChars.
PathTooLongException The specified path, file name, or both exceed the system-defined maximum length. 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.

Examples

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

Public Sub Main()
    Const Path As String = "C:\Temp\MyTest.txt"
    
    If Not File.Exists(Path) Then
        ' Create a file to write to.
        Dim sw As StreamWriter
        Set sw = File.CreateText(Path)
        
        sw.WriteLine "Hello"
        sw.WriteLine "And"
        sw.WriteLine "Welcome"
        sw.Flush
        sw.CloseWriter
    End If

    ' Open the file to read from.
    Dim sr As StreamReader
    Set sr = File.OpenText(Path)
    
    Do While sr.Peek >= 0
        Debug.Print sr.ReadLine
    Loop
    
    sr.CloseReader
End Sub

See Also

Project CorLib Overview

Class File Overview

StreamWriter