C#基础:文件操作代码示例

本文介绍了如何在C#中进行基本的文件操作,包括创建文本文件并写入内容,读取文件,复制文件,删除文件,以及创建目录。示例代码涵盖了这些操作,并强调了异常处理的重要性。

在这里插入图片描述

在C#中,文件操作主要包括读写、创建、删除等。以下是几个C#文件操作的基本示例:

  1. 创建并写入文本文件:
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = @"C:\Temp\MyFile.txt";
        
        // 创建或打开文件以追加模式(如果文件已存在则不会覆盖)
        using (StreamWriter sw = new StreamWriter(filePath, true))
        {
            sw.WriteLine("Hello, World!");
            sw.WriteLine("This is a test line.");
        }
    }
}
  1. 读取文本文件内容:
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = @"C:\Temp\MyFile.txt";

        // 打开文件进行读取
        using (StreamReader sr = new StreamReader(filePath))
        {
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
        }
    }
}
  1. 复制文件:
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string sourcePath = @"C:\Temp\OriginalFile.txt";
        string destinationPath = @"C:\Temp\CopiedFile.txt";

        // 复制文件
        File.Copy(sourcePath, destinationPath, true); // 第三个参数为true表示如果目标文件已存在则覆盖它
    }
}

4. **删除文件:**

```csharp
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = @"C:\Temp\ToDelete.txt";

        // 检查文件是否存在,如果存在则删除
        if (File.Exists(filePath))
        {
            File.Delete(filePath);
            Console.WriteLine($"File {filePath} has been deleted.");
        }
        else
        {
            Console.WriteLine($"File {filePath} does not exist.");
        }
    }
}
  1. 创建目录及文件:
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string directoryPath = @"C:\Temp\NewDirectory";
        string filePath = Path.Combine(directoryPath, "NewFile.txt");

        // 创建目录(如果不存在)
        Directory.CreateDirectory(directoryPath);

        // 创建并写入文件
        using (StreamWriter sw = new StreamWriter(filePath))
        {
            sw.WriteLine("Content of the new file.");
        }

        Console.WriteLine($"Directory {directoryPath} and file {filePath} have been created.");
    }
}

以上代码片段展示了如何使用C#进行基本的文件和目录操作,包括创建、写入、读取、复制和删除文件以及创建目录。记得处理可能发生的异常,如权限不足、路径无效等。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学亮编程手记

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值