description | title | ms.date | helpviewer_keywords | ms.assetid | ||||
---|---|---|---|---|---|---|---|---|
Learn more about: How to: Write Text to Files in Visual Basic |
How to: Write Text to Files |
07/20/2015 |
|
304956eb-530d-4df7-b48f-9b4d1f2581a0 |
The xref:Microsoft.VisualBasic.FileIO.FileSystem.WriteAllText%2A method can be used to write text to files. If the specified file does not exist, it is created.
-
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 namedtest.txt
, appending the text to any existing text in the file.[!code-vbVbFileIOWrite#3]
-
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 settingappend
toTrue
.This example writes the names of the files in the
Documents and Settings
directory toFileList.txt
, inserting a carriage return between each for better readability.[!code-vbVbFileIOWrite#4]
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 \\.\) (xref:System.ArgumentException).
-
The path is not valid because it is
Nothing
(xref:System.ArgumentNullException). -
File
points to a path that does not exist (xref:System.IO.FileNotFoundException or xref:System.IO.DirectoryNotFoundException). -
The file is in use by another process, or an I/O error occurs (xref:System.IO.IOException).
-
The path exceeds the system-defined maximum length (xref:System.IO.PathTooLongException).
-
A file or directory name in the path contains a colon (:) or is in an invalid format (xref:System.NotSupportedException).
-
The user lacks necessary permissions to view the path (xref:System.Security.SecurityException).
-
The disk is full, and the call to
WriteAllText
fails (xref:System.IO.IOException).
If you are running in a partial-trust context, the code might throw an exception due to insufficient privileges. For more information, see Code Access Security Basics.
- xref:Microsoft.VisualBasic.FileIO.FileSystem
- xref:Microsoft.VisualBasic.FileIO.FileSystem.WriteAllText%2A
- How to: Read from Text Files