网站首页 > 博客文章 正文
一、简单的文件操作
C# 提供了丰富的文件操作功能,可以实现文件的创建、读取、写入、复制、移动、删除等操作。以下是一些常用的文件操作示例:
1.创建文件:
using System.IO;
string filePath = @"C:\test.txt";
File.Create(filePath);
2.读取文件中的内容:
using System.IO;
string filePath = @"C:\test.txt";
string fileContent = File.ReadAllText(filePath);
3.写入文件:
using System.IO;
string filePath = @"C:\test.txt";
string fileContent = "Hello World!";
File.WriteAllText(filePath, fileContent);
4.复制文件:
using System.IO;
string sourceFilePath = @"C:\test.txt";
string destinationFilePath = @"C:\temp\test.txt";
File.Copy(sourceFilePath, destinationFilePath);
5.移动文件:
using System.IO;
string sourceFilePath = @"C:\test.txt";
string destinationFilePath = @"C:\temp\test.txt";
File.Move(sourceFilePath, destinationFilePath);
6.删除文件:
using System.IO;
string filePath = @"C:\test.txt";
File.Delete(filePath);
以上是一些常用的文件操作示例,你可以根据自己的实际需求进行相应的操作。
二、使用内存流操作文件
在 C# 中,使用内存流(MemoryStream)可以在内存中读写文件,而不必通过硬盘或其他外部存储介质。这种方式对于处理小文件或实时生成文件内容非常有用。以下是一些常用的内存流操作示例:
1.从文件加载数据到内存流:
using System.IO;
string filePath = @"C:\test.txt";
byte[] fileBytes = File.ReadAllBytes(filePath);
MemoryStream memoryStream = new MemoryStream(fileBytes);
以上代码读取了 test.txt 文件的数据,并将其存储在内存流中。
2.从内存流中读取数据:
using System.IO;
string filePath = @"C:\test.txt";
byte[] fileBytes = File.ReadAllBytes(filePath);
MemoryStream memoryStream = new MemoryStream(fileBytes);
byte[] buffer = new byte[1024];
int bytesRead = memoryStream.Read(buffer, 0, buffer.Length);
以上代码通过内存流读取了数据并存储在 buffer 中,bytesRead 变量表示实际读取的字节数。
3.向内存流中写入数据:
using System.IO;
MemoryStream memoryStream = new MemoryStream();
string message = "Hello World!";
byte[] messageBytes = Encoding.UTF8.GetBytes(message);
memoryStream.Write(messageBytes, 0, messageBytes.Length);
以上代码将字符串 Hello World! 转换为字节数组后写入内存流中。
4.从内存流中另存为文件:
using System.IO;
string filePath = @"C:\test.txt";
byte[] fileBytes = File.ReadAllBytes(filePath);
MemoryStream memoryStream = new MemoryStream(fileBytes);
string newFilePath = @"C:\new-test.txt";
File.WriteAllBytes(newFilePath, memoryStream.ToArray());
以上代码从内存流中读取数据,然后将其另存为新文件。
以上是一些常用的内存流操作示例,你可以根据自己的实际需求进行相应的操作。需要注意的是,内存流需要消耗系统内存,因此不适用于大文件的处理。
三、处理大文件
在处理大文件时,如果将整个文件读取到内存中,可能会导致内存不足。因此,我们需要使用流(Stream)来读写文件,而不是一次性将整个文件读取到内存中。
以下是一些常用的处理大文件的方法:
1.逐行读取文件:
using System.IO;
string filePath = @"C:\large-file.txt";
using (StreamReader reader = new StreamReader(filePath))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
// TODO: 处理每行数据
}
}
以上代码逐行读取 large-file.txt 文件,并对每行数据进行处理。由于每次只读取一行,因此无需将整个文件读取到内存中。
2.分块读取文件:
using System.IO;
string filePath = @"C:\large-file.txt";
const int BUFFER_SIZE = 1024 * 1024; // 每次读取 1MB 数据
byte[] buffer = new byte[BUFFER_SIZE];
using (FileStream fileStream = File.Open(filePath, FileMode.Open))
{
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
// TODO: 处理每块数据
}
}
以上代码每次读取 1MB 的数据块,然后对每块数据进行处理。由于每次只读取一块,无需将整个文件读取到内存中。
3.并行读取文件:
using System.IO;
using System.Threading.Tasks;
string filePath = @"C:\large-file.txt";
const int BUFFER_SIZE = 1024 * 1024; // 每个任务读取 1MB 数据
byte[] buffer = new byte[BUFFER_SIZE];
using (FileStream fileStream = File.Open(filePath, FileMode.Open))
{
Parallel.ForEach(
Partitioner.Create(0, fileStream.Length, BUFFER_SIZE), // 每个任务读取一定区间的数据
range =>
{
long startPosition = range.Item1;
int length = (int) (range.Item2 - range.Item1);
fileStream.Seek(startPosition, SeekOrigin.Begin);
int bytesRead = fileStream.Read(buffer, 0, length);
// TODO: 处理每个任务的数据
});
}
以上代码使用并行任务读取文件,每个任务只负责读取一定区间的数据。由于并行任务可以充分利用 CPU 的多核心性能,因此能够加速文件读取的过程。
以上是一些常用的处理大文件的方法,你可以根据自己的实际需求进行相应的选择。需要注意的是,在操作大文件时,应优化代码以提高处理性能。
四、使用相对路径操作文件
在 C# 中,相对路径是相对于执行程序的当前工作目录而言的。因此,我们可以使用以下代码来获取当前程序的工作目录:
在 C# 中,相对路径是相对于执行程序的当前工作目录而言的。因此,我们可以使用以下代码来获取当前程序的工作目录:
string currentDirectory = Directory.GetCurrentDirectory();
然后可以使用相对路径拼接出文件的完整路径,比如:
string currentDirectory = Directory.GetCurrentDirectory();
string filePath = Path.Combine(currentDirectory, "data\\test.txt");
上述代码中,我们将文件路径拼接为当前工作目录下的 data\test.txt 文件。注意,在使用相对路径时,路径字符串中的分隔符应使用反斜杠(\)而不是正斜杠(/)。
然后就可以使用前面提到的文件操作代码对文件进行读写控制,比如:
string currentDirectory = Directory.GetCurrentDirectory();
string filePath = Path.Combine(currentDirectory, "data\\test.txt");
// 写入文件
File.WriteAllText(filePath, "Hello World!");
// 读取文件
string fileContent = File.ReadAllText(filePath);
Console.WriteLine(fileContent);
这样就可以在当前程序的工作目录下的 data 文件夹中读写名为 test.txt 的文件了。当然,你也可以根据实际需求修改具体的路径。
以上是使用 C# 操作文件的粗浅理解,如有不足之处还望指正。
创作不易,如果喜欢还请点赞关注,谢谢!
猜你喜欢
- 2024-10-15 Python 速度慢,试试这个方法提高 1000 倍
- 2024-10-15 从零开始自学C#基础的第十五天——数组的基本用法
- 2024-10-15 浅谈C#取消令牌CancellationTokenSource
- 2024-10-15 总结了才知道,原来channel有这么多用法
- 2024-10-15 面向对象(8-15)异常类-C#编程零基础到入门学习
- 2024-10-15 .NET 6 中 LINQ 的改进(.net 调优)
- 2024-10-15 Log4net配置文件 C#(c# log4j)
- 2024-10-15 C# BIN文件读取以及CRC校验(匹配STM32F103)
- 2024-10-15 C#如何对String中的Contact/Join方法进行优化的
- 2024-10-15 .NET 中的值对象(DDD 基础知识)(.net的数据类型)
你 发表评论:
欢迎- 最近发表
-
- 给3D Slicer添加Python第三方插件库
- Python自动化——pytest常用插件详解
- Pycharm下安装MicroPython Tools插件(ESP32开发板)
- IntelliJ IDEA 2025.1.3 发布(idea 2020)
- IDEA+Continue插件+DeepSeek:开发者效率飙升的「三体组合」!
- Cursor:提升Python开发效率的必备IDE及插件安装指南
- 日本旅行时想借厕所、买香烟怎么办?便利商店里能解决大问题!
- 11天!日本史上最长黄金周来了!旅游万金句总结!
- 北川景子&DAIGO缘定1.11 召开记者会宣布结婚
- PIKO‘PPAP’ 洗脑歌登上美国告示牌
- 标签列表
-
- ifneq (61)
- messagesource (56)
- aspose.pdf破解版 (56)
- promise.race (63)
- 2019cad序列号和密钥激活码 (62)
- window.performance (66)
- qt删除文件夹 (72)
- mysqlcaching_sha2_password (64)
- ubuntu升级gcc (58)
- nacos启动失败 (64)
- ssh-add (70)
- jwt漏洞 (58)
- macos14下载 (58)
- yarnnode (62)
- abstractqueuedsynchronizer (64)
- source~/.bashrc没有那个文件或目录 (65)
- springboot整合activiti工作流 (70)
- jmeter插件下载 (61)
- 抓包分析 (60)
- idea创建mavenweb项目 (65)
- vue回到顶部 (57)
- qcombobox样式表 (68)
- vue数组concat (56)
- tomcatundertow (58)
- pastemac (61)
本文暂时没有评论,来添加一个吧(●'◡'●)