HOW TO:將文字寫入檔案

更新:2007 年 11 月

下列程式碼範例將示範如何將文字寫入文字檔。

第一個範例會示範如何將文字寫入現有的檔案中,第二個範例則會示範如何建立新的文字檔,並將字串寫入到這個檔案中。WriteAllText 方法也能提供類似的功能。

注意事項:

Visual Basic 使用者可以選擇對檔案 I/O 使用 My.Computer.FileSystem 物件所提供的方法和屬性。如需詳細資訊,請參閱 My.Computer.FileSystem 物件

範例

Imports System
Imports System.IO

Class Test
    Public Shared Sub Main()
        ' Create an instance of StreamWriter to write text to a file.
        Using sw As StreamWriter = New StreamWriter("TestFile.txt")
            ' Add some text to the file.
            sw.Write("This is the ")
            sw.WriteLine("header for the file.")
            sw.WriteLine("-------------------")
            ' Arbitrary objects can also be written to the file.
            sw.Write("The date is: ")
            sw.WriteLine(DateTime.Now)
            sw.Close()
        End Using
    End Sub
End Class
using System;
using System.IO;

class Test 
{
    public static void Main() 
    {
        // Create an instance of StreamWriter to write text to a file.
        // The using statement also closes the StreamWriter.
        using (StreamWriter sw = new StreamWriter("TestFile.txt")) 
        {
            // Add some text to the file.
            sw.Write("This is the ");
            sw.WriteLine("header for the file.");
            sw.WriteLine("-------------------");
            // Arbitrary objects can also be written to the file.
            sw.Write("The date is: ");
            sw.WriteLine(DateTime.Now);
        }
    }
}
Option Explicit On 
Option Strict On
Imports System
Imports System.IO
Public Class TextToFile
    Private Const FILE_NAME As String = "MyFile.txt"
    Public Shared Sub Main()
        If File.Exists(FILE_NAME) Then
            Console.WriteLine("{0} already exists.", FILE_NAME)
            Return
        End If
        Using sw As StreamWriter = File.CreateText(FILE_NAME)
            sw.WriteLine("This is my file.")
            sw.WriteLine("I can write ints {0} or floats {1}, and so on.", 1, 4.2)
            sw.Close()
        End Using
    End Sub
End Class
using System;
using System.IO;
public class TextToFile 
{
    private const string FILE_NAME = "MyFile.txt";
    public static void Main(String[] args) 
    {
        if (File.Exists(FILE_NAME)) 
        {
            Console.WriteLine("{0} already exists.", FILE_NAME);
            return;
        }
        using (StreamWriter sw = File.CreateText(FILE_NAME))
        {
            sw.WriteLine ("This is my file.");
            sw.WriteLine ("I can write ints {0} or floats {1}, and so on.", 
                1, 4.2);
            sw.Close();
        }
    }
}

請參閱

工作

HOW TO:建立目錄清單

HOW TO:讀取和寫入新建立的資料檔案

HOW TO:開啟並附加至記錄檔

HOW TO:從檔案讀取文字

HOW TO:從字串中讀取字元

HOW TO:將字元寫入至字串

概念

基本檔案 I/O

參考

StreamWriter

File.CreateText