如何:在 Visual Basic 中向文件内写入文本

更新:2007 年 11 月

My.Computer.FileSystem.WriteAllText 方法可以用于向文件中写入文本。如果指定的文件不存在,则创建该文件。

过程

向文件中写入文本

  • 使用 WriteAllText 方法向文件中写入文本,同时指定要写入的文件和文本。此示例向名为 test.txt 的文件中写入 "This is new text." 这一行,并将这行文本追加到此文件中现有的任何文本之后。

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

向文件中写入一系列字符串

  • 循环通过字符串集合。使用 WriteAllText 方法向文件中写入文本,同时指定目标文件以及要添加的字符串,并将 append 设置为 True。

    此示例将 Documents and Settings 目录中文件的名称写入 FileList.txt 中,同时在每个名称之间插入一个回车符以获得更好的可读性。

    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
    

可靠编程

以下情况可能会导致异常:

如果在部分信任的上下文中运行,则代码可能会因特权不足而引发一个异常。有关更多信息,请参见代码访问安全性基础知识

请参见

任务

如何:在 Visual Basic 中读取文本文件

参考

My.Computer.FileSystem 对象

My.Computer.FileSystem.WriteAllText 方法