Writes text to a file.
' Usage My.Computer.FileSystem.WriteAllText(file ,text ,append) My.Computer.FileSystem.WriteAllText(file ,text ,append ,encoding) ' Declaration Public Sub WriteAllText( _ ByVal file As String, _ ByVal text As String, _ ByVal append As Boolean _ ) ' -or- Public Sub WriteAllText( _ ByVal file As String, _ ByVal text As String, _ ByVal append As Boolean, _ ByVal encoding As System.Text.Encoding _ )
The following conditions may cause an exception:
The path is not valid because of one of the following reasons: it is a zero-length string; it contains only white space; it contains invalid characters, ends with a trailing slash, or is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The file is being used by another process, or an I/O error occurs (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
If you are running in a partial-trust context, the code might throw an exception because of insufficient permissions. For more information, see Code Access Security Basics.
When no encoding is specified, UTF-8 is used. The byte order mark (BOM) for the encoding is written to the file unless you specify Encoding.Default, which uses the system's current ANSI code page. If the specified encoding does not match the existing encoding of the file, the specified encoding is ignored.
If the specified path, excluding the file name, is not valid, a DirectoryNotFoundException exception is thrown. If the path is valid but the file does not exist, the file is created.
If the append parameter is True, the method appends the text to the file; otherwise existing text in the file is overwritten.
The WriteAllText method opens a file, writes to it, and then closes it. Code that uses the WriteAllText method is simpler than code that uses a StreamWriter object. However, if you are adding strings to a file by using a loop, a StreamWriter object can provide better performance because you only have to open and close the file one time. For more information, see My.Computer.FileSystem.OpenTextFileWriter Method.
This example writes the line "This is new text to be added." to the file Test.txt, overwriting any existing text in the file.
This example writes the names of the files in the Documents and Settings folder to FileList.txt, inserting a carriage return between each for better readability.
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Windows Control Library
Web Control Library