以下是关于文件读写和优化的示例代码:
文件的读取:
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "path_to_file.txt";
// 一次性读取整个文件内容为字符串
string fileContent = File.ReadAllText(filePath);
Console.WriteLine(fileContent);
// 按行读取文件内容为字符串数组
string[] lines = File.ReadAllLines(filePath);
foreach (string line in lines)
{
Console.WriteLine(line);
}
}
}
文件的写入:
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "path_to_file.txt";
// 写入字符串到文件
string content = "Hello, World!";
File.WriteAllText(filePath, content);
// 写入字符串数组到文件
string[] lines = { "Line 1", "Line 2", "Line 3" };
File.WriteAllLines(filePath, lines);
}
}
读取大文件的优化:
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "path_to_large_file.txt";
// 逐行读取大文件内容
using (StreamReader reader = new StreamReader(filePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
写入大文件的优化:
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "path_to_large_file.txt";
// 逐行写入大文件内容
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.WriteLine("Line 1");
writer.WriteLine("Line 2");
writer.WriteLine("Line 3");
}
}
}
二进制文件的读写:
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "path_to_binary_file.bin";
// 读取二进制文件
using (BinaryReader reader = new BinaryReader(File.Open(filePath, FileMode.Open)))
{
int intValue = reader.ReadInt32();
string stringValue = reader.ReadString();
Console.WriteLine(intValue);
Console.WriteLine(stringValue);
}
// 写入二进制文件
using (BinaryWriter writer = new BinaryWriter(File.Open(filePath, FileMode.Create)))
{
int intValue = 123;
string stringValue = "Hello, World!";
writer.Write(intValue);
writer.Write(stringValue);
}
}
}
异步文件读取:
using System;
using System.IO;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
string filePath = "path_to_large_file.txt";
using (StreamReader reader = new StreamReader(filePath))
{
string line;
while ((line = await reader.ReadLineAsync()) != null)
{
Console.WriteLine(line);
}
}
}
}
上述代码提供了一些常见的文件读写操作和优化技巧的示例,你可以根据自己的需求进行修改和扩展。请替换path_to_file.txt
和path_to_large_file.txt
为实际的文件路径。