Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# 文件操作

作者:魔影杀戮   发布日期:2026-03-30   浏览:88

using System;
using System.IO;

class FileOperationsExample
{
    static void Main()
    {
        string filePath = "example.txt";

        // 创建文件并写入内容
        using (StreamWriter writer = new StreamWriter(filePath))
        {
            writer.WriteLine("Hello, World!");
        }

        // 读取文件内容
        using (StreamReader reader = new StreamReader(filePath))
        {
            string content = reader.ReadToEnd();
            Console.WriteLine("File content:");
            Console.WriteLine(content);
        }

        // 检查文件是否存在
        if (File.Exists(filePath))
        {
            Console.WriteLine($"File '{filePath}' exists.");
        }
        else
        {
            Console.WriteLine($"File '{filePath}' does not exist.");
        }

        // 删除文件
        File.Delete(filePath);
        Console.WriteLine($"File '{filePath}' has been deleted.");
    }
}

解释说明:

  1. 创建文件并写入内容:使用 StreamWriter 类来创建一个文件并在其中写入文本。using 语句确保流在操作完成后被正确关闭。
  2. 读取文件内容:使用 StreamReader 类读取文件内容,并将其打印到控制台。
  3. 检查文件是否存在:使用 File.Exists 方法检查指定路径的文件是否存在。
  4. 删除文件:使用 File.Delete 方法删除指定的文件。

以上代码展示了如何在 C# 中进行基本的文件操作,包括创建、读取、检查和删除文件。

上一篇:c# webrtc

下一篇:c#string分割

大家都在看

c# 二进制

c# 创建目录

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站