Udostępnij za pośrednictwem


How to: Write Text to Files in Visual Basic

The My.Computer.FileSystem.WriteAllText Method can be used to write text to files. If the specified file does not exist, it is created.

Procedure

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.

    My.Computer.FileSystem.WriteAllText("C:\TestFolder1\test.txt", _
    "This is new text to be added.",True)
    

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.

    For Each foundFile As String In _
    My.Computer.FileSystem.GetFiles("C:\Documents and Settings")
    foundFile = foundFile & vbCrLf
    My.Computer.FileSystem.WriteAllText _
    ("C:\Documents and Settings\FileList.txt", foundFile, True)
    Next
    

Robust Programming

The following conditions may cause an exception:

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.

See Also

Tasks

How to: Read From Text Files in Visual Basic

Reference

My.Computer.FileSystem Object

My.Computer.FileSystem.WriteAllText Method