如何:向文件写入文本

下面的示例演示如何向文本文件中写入文本。 此示例使用 "*.txt" 搜索模式从用户的**“我的文档”**文件夹中读取所有文本文件,并将这些文件写入一个大型文本文件。

注意注意

Visual Basic 用户可以选择使用由 Microsoft.VisualBasic.FileIO.FileSystem 类提供的方法和属性执行文件 I/O 操作。

示例

Imports System
Imports System.IO
Imports System.Text
Imports System.Collections.Generic

Class Program

    Public Shared Sub Main(ByVal args As String())

        Dim mydocpath As String = _
        Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
        Dim sb As New StringBuilder()

        For Each txtName As String _
            In Directory.EnumerateFiles(mydocpath, "*.txt")
            Using sr As New StreamReader(txtName)
                sb.AppendLine(txtName.ToString())
                sb.AppendLine("= = = = = =")
                sb.Append(sr.ReadToEnd())
                sb.AppendLine()
                sb.AppendLine()

            End Using
        Next

        Using outfile As New StreamWriter(mydocpath & "\AllTxtFiles.txt")
            outfile.Write(sb.ToString())
        End Using
    End Sub
End Class
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;

class Program
{

    static void Main(string[] args)
    {

        string mydocpath = 
            Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        StringBuilder sb = new StringBuilder();

        foreach (string txtName in Directory.EnumerateFiles(mydocpath,"*.txt"))
        {
            using (StreamReader sr = new StreamReader(txtName))
            {
                sb.AppendLine(txtName.ToString());
                sb.AppendLine("= = = = = =");
                sb.Append(sr.ReadToEnd());
                sb.AppendLine();
                sb.AppendLine();
            }

        }

        using (StreamWriter outfile = 
            new StreamWriter(mydocpath + @"\AllTxtFiles.txt"))
        {
            outfile.Write(sb.ToString());
        }
    }
}
using namespace System;
using namespace System::IO;
using namespace System::Text;
using namespace System::Collections::Generic;

ref class Program
{
public:
    static void Main()
    {
        String^ mydocpath =
            Environment::GetFolderPath(Environment::SpecialFolder::MyDocuments);
        StringBuilder^ sb = gcnew StringBuilder();

        for each (String^ txtName in Directory::EnumerateFiles(mydocpath, "*.txt"))
        {
            StreamReader^ sr = gcnew StreamReader(txtName);
            sb->AppendLine(txtName->ToString());
            sb->AppendLine("= = = = = =");
            sb->Append(sr->ReadToEnd());
            sb->AppendLine();
            sb->AppendLine();
            sr->Close();
        }

        StreamWriter^ outfile = gcnew StreamWriter(mydocpath + "\\AllTxtFiles.txt");
        outfile->Write(sb->ToString());
        outfile->Close();
    }
};

int main()
{
    Program::Main();
}

请参见

任务

如何:创建目录列表

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

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

如何:从文件读取文本

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

如何:向字符串写入字符

参考

StreamWriter

File.CreateText

概念

基本的文件 I/O