C#文件的创建、读取、写入和删除

在 C# 中,你可以使用 System.IO 命名空间中的类来创建、读取、写入和删除文件。

以下是一个示例代码:

using System;
using System.IO;
namespace FileExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // 创建文件
            string filePath = @"C:\example.txt";
            if (!File.Exists(filePath))
            {
                using (FileStream fs = File.Create(filePath))
                {
                    Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
                    fs.Write(info, 0, info.Length);
                }
            }
            // 读取文件
            string fileContent;
            using (StreamReader sr = File.OpenText(filePath))
            {
                fileContent = sr.ReadToEnd();
                Console.WriteLine("File content: " + fileContent);
            }
            // 写入文件
            using (StreamWriter sw = File.CreateText(filePath))
            {
                sw.WriteLine("This is additional text added to the file.");
            }
            // 删除文件
            File.Delete(filePath);
        }
    }
}

在这个示例中,我们首先检查文件是否存在,如果不存在,则使用 File.Create 方法创建一个新文件。接下来,我们使用 StreamReader 读取文件内容,并使用 StreamWriter 写入文件。最后,我们使用 File.Delete 删除文件。


果糖网