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

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

感情恋爱合集

职业发展故事

常用代码片段

程序开发教程

自我备考经验

相关推荐
hez20103 天前
在 .NET 上构建超大托管数组
c#·.net·.net core·gc·clr
雨落倾城夏未凉8 天前
第四章c#方法-参数数组和可选参数(16)
后端·c#
唐青枫9 天前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
唐青枫10 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
咕白m62510 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net
用户917215619021110 天前
C# 通信协议增量解析:用状态机处理半包和粘包
c#
小码编匠11 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net
唐青枫13 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech14 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf15 天前
C#摸鱼实录——IoC与DI案例详解
c#