亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> C语言

C# 文件操作实战指南:Exists、ReadAllLines、ReadAllText、Copy、Delete

C# 文件操作实战指南

在 C# 和 .NET 中处理文件是常见需求。无论验证文件存在、读取内容、管理文件复制,System.IO.File 类提供直观、线程安全的方法。下面给出简明解释和遵循最佳实践及微软官方指导的示例代码。

基本文件操作

  1. 读取 – 从现有文件检索数据。
  2. 写入 – 用新内容覆盖整个文件(默认行为)。
  3. 追加 – 在不删除现有内容情况下向文件末尾添加数据。

覆盖的关键方法

前置条件

所有示例假设文本文件 D:\Example.txt 存在,内容两行:

 Guru99 – .Net
Guru99 – C# 

1. 检查文件存在 – File.Exists

using System;
using System.IO;
namespace DemoApplication {
    class Tutorial {
        static void Main(string[] args) {
            string path = "D:\\Example.txt";
            if (File.Exists(path)) {
                Console.WriteLine("File Exists");
            } else {
                Console.WriteLine("File Not Found");
            }
            Console.ReadKey();
        }
    }
}

当 D:\Example.txt 存在时程序输出 File Exists。

2. 逐行读取 – File.ReadAllLines

using System;
using System.IO;
namespace DemoApplication {
    class Tutorial {
        static void Main(string[] args) {
            string path = "D:\\Example.txt";
            string[] lines = File.ReadAllLines(path);
            foreach (var line in lines) {
                Console.WriteLine(line);
            }
            Console.ReadKey();
        }
    }
}

文件每行在控制台单独打印。

3. 读取整个文件 – File.ReadAllText

using System;
using System.IO;
namespace DemoApplication {
    class Tutorial {
        static void Main(string[] args) {
            string path = "D:\\Example.txt";
            string content = File.ReadAllText(path);
            Console.WriteLine(content);
            Console.ReadKey();
        }
    }
}

控制台显示两行并以换行符连接。

4. 复制文件 – File.Copy

using System;
using System.IO;
namespace DemoApplication {
    class Tutorial {
        static void Main(string[] args) {
            string source = "D:\\Example.txt";
            string destination = "D:\\ExampleNew.txt";
            File.Copy(source, destination, overwrite: true);
            Console.WriteLine("Copy succeeded");
            Console.ReadKey();
        }
    }
}

新文件 D:\ExampleNew.txt 包含 Example.txt 的确切副本。

5. 删除文件 – File.Delete

using System;
using System.IO;
namespace DemoApplication {
    class Tutorial {
        static void Main(string[] args) {
            string path = "D:\\Example.txt";
            File.Delete(path);
            Console.WriteLine("File deleted");
            Console.ReadKey();
        }
    }
}

执行后 D:\Example.txt 从 D 盘永久移除。

总结

C语言

  1. 单点I/O保护:熔断器还是断路器?
  2. Axiomtek IPS960-511-PoE:面向工业检测的一体化坚固视觉控制器
  3. 掌握 C# using 指令:命名空间导入、别名与静态导入全解析
  4. C 语言输入输出(I/O)精通:scanf() 与 printf() 详解
  5. C语言文件处理完全指南:fopen、fprintf、fread 与 fseek
  6. C 语言文件 I/O 实战:创建、打开、读写与二进制操作
  7. C 语言头文件详解:类型、用法与最佳实践
  8. C 语言错误处理最佳实践:errno、perror 与 strerror 详解
  9. C# 异常处理完全指南:try-catch-finally、异常类型、自定义异常与最佳实践
  10. C# 文件 I/O 完全指南:流、读写操作与文件系统管理
  11. Python 文件 I/O:掌握文件操作、读写与管理
  12. Python 文件 I/O:掌握输入输出操作