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);

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

感情恋爱合集

职业发展故事

常用代码片段

程序开发教程

自我备考经验

相关推荐
Highcharts.js4 小时前
教程:基于 React + Highcharts 构建一个单页应用程序、按需数据拉取与图表渲染
开发语言·前端·数据结构·react.js·前端框架·highcharts·页面应用
头发还在的女程序员5 小时前
医院陪诊管理系统怎么选择?——2026 年选型避坑与架构参考
java·开发语言·陪诊系统·陪诊app·医院陪诊陪护
爱写代码的小朋友7 小时前
从零开始学 Win32 API:C++ 窗口编程实战(VS Code + MinGW-w64 命令行详解)
开发语言·c++
果汁华7 小时前
Function Calling 与 Python 实战完整指南
开发语言·网络·python
小小晓.8 小时前
C++:语句和作用域
开发语言·c++
wanderist.8 小时前
Lambda表达式在算法竞赛中的应用
java·开发语言·算法
海天鹰9 小时前
PHP上传文件
android·开发语言·php
Yeauty11 小时前
渲染成图再 CLI 拼接,还是进程内直推?Rust 帧到视频的两条路
开发语言·rust·音视频
geovindu11 小时前
CSharp: Breadth First Search Algorithm and Depth First Search Algorithm
开发语言·后端·算法·c#·.net·搜索算法
库克克12 小时前
【C++】set 与multiset
开发语言·c++