在C#中,文件的输入和输出通常涉及到 System.IO 命名空间中的类和方法。以下是一些基本的文件输入和输出操作:

文件写入(File Output):

使用 StreamWriter 类可以方便地向文件中写入数据。以下是一个简单的文件写入示例:
using System;
using System.IO;

class Program
{
    static void Main()
    {
        // 指定文件路径
        string filePath = "example.txt";

        // 使用 StreamWriter 写入文件
        using (StreamWriter writer = new StreamWriter(filePath))
        {
            writer.WriteLine("Hello, World!");
            writer.WriteLine("This is a C# file write example.");
        }

        Console.WriteLine("File write operation completed.");
    }
}

文件读取(File Input):

使用 StreamReader 类可以从文件中读取数据。以下是一个简单的文件读取示例:
using System;
using System.IO;

class Program
{
    static void Main()
    {
        // 指定文件路径
        string filePath = "example.txt";

        // 使用 StreamReader 读取文件
        using (StreamReader reader = new StreamReader(filePath))
        {
            // 读取文件的每一行
            while (!reader.EndOfStream)
            {
                string line = reader.ReadLine();
                Console.WriteLine(line);
            }
        }
    }
}

文件追加(File Append):

如果需要将数据追加到现有文件末尾,可以使用 StreamWriter 的构造函数中的 true 参数,指示以追加模式打开文件:
using System;
using System.IO;

class Program
{
    static void Main()
    {
        // 指定文件路径
        string filePath = "example.txt";

        // 使用 StreamWriter 以追加模式写入文件
        using (StreamWriter writer = new StreamWriter(filePath, true))
        {
            writer.WriteLine("This line is appended to the file.");
        }

        Console.WriteLine("File append operation completed.");
    }
}

这些示例涵盖了文件的基本输入和输出操作。请注意,在使用文件操作时,应该确保适当地处理异常,例如文件不存在或没有读取/写入权限。此外,使用 using 语句可以确保在使用完 StreamWriter 或 StreamReader 后正确关闭文件。


转载请注明出处:http://www.pingtaimeng.com/article/detail/14767/C#