File: AppendAllText

AppendAllText

Appends the specified string to the file, creating the file if it does not already exist.



 Public Sub AppendAllText(
	  ByRef Path As String,
	  ByRef Contents As String,
	  Optional ByVal Encoding As Encoding )

Parameters

Path
[ByRef] String. The file to append the specified string to.
Contents
[ByRef] String. The string to append to the file.
Encoding
[ByVal] Optional. Encoding. The character encoding to use (Default UTF8).

Remarks

Given a string and a file path, this method opens the specified file, appends the string to the end of the file using the specified encoding, and then closes the file. The file handle is guaranteed to be closed by this method, even if exceptions are raised.

Exceptions

ExceptionCondition
UnauthorizedAccessException Path is read-only.
-or-
Path is a directory.
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 code example demonstrates the use of the AppendAllText method to add extra text to the end of a file. In this example a file is created, if it doesnt already exist, and text is added to it.

Public Sub Main()
    Const Path As String = "c:\temp\MyTest.txt"
    Dim sw As StreamWriter

    ' This text is added only once to the file.
    If Not File.Exists(Path) Then

        ' Create a file to write to.
        Dim CreateText As String
        CreateText = "Hello and Welcome" & Environment.NewLine
        File.WriteAllText Path, CreateText, Encoding.UTF8
    End If

    ' This text is always added, making the file longer over time
    ' if it is not deleted.
    Dim AppendText As String
    AppendText = "This is extra text" & Environment.NewLine
    File.AppendAllText Path, AppendText, Encoding.UTF8

    ' Open the file to read from.
    Dim ReadText As String
    ReadText = File.ReadAllText(Path)
    Debug.Print ReadText
End Sub

See Also

Project CorLib Overview

Class File Overview