共用方式為


如何:在 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

另請參閱