如何:在 Visual Basic 中將文字寫入檔案

WriteAllText 方法可用來將文字寫入檔案。 如果指定的檔案不存在,則會建立該檔案。

程序

將文字寫入檔案

  • 使用 WriteAllText 方法,將文字寫入檔案中,並指定要寫入的檔案和文字。 這個範例會將 "This is new text." 行寫入名為 test.txt 的檔案,並將文字附加至檔案中的任何現有文字。

    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
    

穩固程式設計

以下條件可能會造成例外狀況:

如果要在部分信任內容中執行,則程式碼可能會因權限不足而擲回例外狀況。 如需詳細資訊,請參閱 Code Access Security Basics

另請參閱