C#File文件基础操作大全

见过不少人、经过不少事、也吃过不少苦,感悟世事无常、人心多变,靠着回忆将往事串珠成链,聊聊感情、谈谈发展,我慢慢写、你一点一点看......

1.创建文件

string filePath = ``@"c:\myFile.txt"``;

FileStream fileStream = File.Create(filePath);

fileStream.Close();

2.文件写入

string content = ``"写入内容"``;

File.WriteAllText(filePath, content, Encoding.UTF8);

3.文件读取(读取成字符串)

string content = File.ReadAllText(filePath,Encoding.UTF8);

4.文件读取(读取成数组)

string[] content = File.ReadAllLines(filePath, Encoding.UTF8);

for (``int i = 0; i < content.Length; i++)

{

``Console.WriteLine(content[i]);

}

5.采用流(Stream)的方式来读取内容

//初始化FileStream

FileStream fs = ``new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None);

StreamReader sr4 = ``new StreamReader(fs, Encoding.UTF8);

string line = ``string``.Empty;

while``((line = sr4.ReadLine()) != ``null``)

{

``Console.WriteLine(line);

}

sr4.Close();

6.采取流方式一次读完

StreamReader sr = ``new StreamReader(filePath, Encoding.UTF8);

string content = sr.ReadToEnd();

Console.WriteLine(content);

sr.Close();

7.文件复制

string sourceFilePath = ``@"c:\myFile.txt"``;

string destinationFilePath = ``@"d:\myFile_copy.txt"``;

File.Copy(sourceFilePath, destinationFilePath);

8.文件移动

string sourceFilePath = ``@"c:\myFile.txt"``;

string destinationFilePath = ``@"d:\myFile.txt"``;

File.Move(sourceFilePath, destinationFilePath);

9.文件重命名

string filePath = ``@"c:\myFile.txt"``;

string newFilePath = ``@"d:\myFile_new.txt"``;

File.Move(filePath, newFilePath);

10.文件删除

string newFilePath = ``@"d:\myFile_new.txt"``;

File.Delete(newFilePath);

关注我,不失联。有啥问题请留言。

感情恋爱合集

职业发展故事

常用代码片段

程序开发教程

自我备考经验

相关推荐
小小龙学IT1 分钟前
Go 后端开发实战:构建高性能 RESTful API 服务
开发语言·golang·restful
fengxin_rou9 分钟前
深入理解Java类加载机制:从原理到实战详解
java·开发语言
薇茗11 分钟前
【C++】类与对象 核心篇
开发语言·c++
AI浩13 分钟前
【数据处理】基于 SAM3 的 LabelMe 标注统一校正方法
android·开发语言·kotlin
原来是猿17 分钟前
理解 C++ 哈希表的原理与工程实践
开发语言·c++·散列表
雪的季节19 分钟前
Qt 自定义表头
开发语言·qt
C137的本贾尼28 分钟前
JDBC 编程:用 Java 连接 MySQL
java·开发语言·mysql
AI视觉网奇31 分钟前
three-bvh-csg glb分割
开发语言·前端·javascript
牢姐与蒯33 分钟前
c++数据结构之c++11(二)
开发语言·c++
z2005093036 分钟前
【linux学习】深入理解 Linux 进程间通信:管道的艺术与实现
linux·开发语言