|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.|
How to: Write Text to Files in Visual Basic
Thecan be used to write text to files. If the specified file does not exist, it is created.
To write text to a file
Use the WriteAllText method to write text to a file, specifying the file and text to be written. This example writes the line "This is new text." to the file named test.txt, appending the text to any existing text in the file.
To write a series of strings to a file
Loop through the string collection. Use the WriteAllText method to write text to a file, specifying the target file and string to be added and setting append to True.
This example writes the names of the files in the Documents and Settings directory to FileList.txt, inserting a carriage return between each for better readability.
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains invalid characters, or it is a device path (starts with \\.\) ().
The path is not valid because it is Nothing ().
File points to a path that does not exist ( or ).
The file is in use by another process, or an I/O error occurs ().
The path exceeds the system-defined maximum length ().
A file or directory name in the path contains a colon (:) or is in an invalid format ().
The user lacks necessary permissions to view the path ().
The disk is full, and the call to WriteAllText fails (IOException).
If you are running in a partial-trust context, the code might throw an exception due to insufficient privileges. For more information, see.