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

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

感情恋爱合集

职业发展故事

常用代码片段

程序开发教程

自我备考经验

相关推荐
mifengxing12 分钟前
Java TreeSet
java·开发语言
m0_5191964043 分钟前
【设计模式】java的习题
开发语言·python
我命由我123451 小时前
Jetpack Compose - Material Design 断点范围、WindowSizeClass、针对不同屏幕尺寸创建预览、四类导航栏
android·java·开发语言·java-ee·kotlin·android jetpack·android runtime
BerrySen1781 小时前
现代 C# 全栈与高性能编程实战指南:从 CLR 底层机制到 AI Agent 智能体架构
人工智能·架构·c#
seacracker1 小时前
一个 Rust 写的存储系统,想把 HPC 和 AI 的存储栈统一了
开发语言·人工智能·rust
captain3761 小时前
多线程进阶
java·开发语言·数据库
在世修行1 小时前
从零打造 C# 工业视觉检测系统(六):OpenCV 图像处理与像素级比例尺标定
opencv·c#·视觉检测
思麟呀2 小时前
C++(八):文件系统库+并行算法
开发语言·c++
郑州光合科技余经理8 小时前
代驾系统架构拆解:订单链路、权限组织与私有化源码交付
开发语言·后端·算法·架构·系统架构·uni-app·php
码哥DFS11 小时前
二叉树的直径
开发语言·javascript·算法