如何:向文件写入文本

更新:2007 年 11 月

下面的代码示例演示如何向文本文件中写入文本。

第一个示例演示如何向现有文件中添加文本。第二个示例演示如何创建一个新文本文件并向其中写入一个字符串。WriteAllText 方法可提供类似的功能。

说明:

Visual Basic 用户可以选择使用由 My.Computer.FileSystem 对象提供的方法和属性进行文件 I/O。有关更多信息,请参见 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();
        }
    }
}

请参见

任务

如何:创建目录列表

如何:对新建的数据文件进行读取和写入

如何:打开并追加到日志文件

如何:从文件读取文本

如何:从字符串中读取字符

如何:向字符串写入字符

概念

基本的文件 I/O

参考

StreamWriter

File.CreateText