专业的编程技术博客社区

网站首页 > 博客文章 正文

C# 文件操作浅析(c#代码文件)

baijin 2024-10-15 08:32:04 博客文章 9 ℃ 0 评论

一、简单的文件操作

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# 操作文件的粗浅理解,如有不足之处还望指正。

创作不易,如果喜欢还请点赞关注,谢谢!

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表