揭秘C#高效文件操作:轻松读写文本、Excel与PDF!

引言
在软件开发过程中,文件操作是必不可少的一环。C#作为一门强大的编程语言,提供了丰富的类库来支持文件操作。本文将详细介绍如何在C#中高效地进行文本、Excel和PDF文件的读写操作。
文本文件操作
1. 读取文本文件
在C#中,可以使用
StreamReader
类来读取文本文件。以下是一个示例代码:
using System;
using System.IO;

class Program
{
static void Main()
{
string filePath = @”C:\example\textfile.txt”;
using (StreamReader reader = new StreamReader(filePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
2. 写入文本文件
可以使用
StreamWriter
类来写入文本文件。以下是一个示例代码:
using System;
using System.IO;

class Program
{
static void Main()
{
string filePath = @”C:\example\textfile.txt”;
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.WriteLine(“Hello, World!”);
writer.WriteLine(“This is a sample text file.”);
}
}
}
Excel文件操作
1. 读取Excel文件
在C#中,可以使用
EPPlus
库来读取Excel文件。以下是一个示例代码:
using System;
using OfficeOpenXml;

class Program
{
static void Main()
{
string filePath = @”C:\example\excelfile.xlsx”;
using (ExcelPackage package = new ExcelPackage(new FileInfo(filePath)))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
for (int row = 1; row <= worksheet.Dimension.End.Row; row++) { for (int col = 1; col <= worksheet.Dimension.End.Column; col++) { Console.WriteLine(worksheet.Cells[row, col].Value); } } } } } 2. 写入Excel文件 同样可以使用 EPPlus 库来写入Excel文件。以下是一个示例代码: using System; using OfficeOpenXml; class Program { static void Main() { string filePath = @"C:\example\excelfile.xlsx"; using (ExcelPackage package = new ExcelPackage()) { ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet1"); worksheet.Cells[1, 1].Value = "Hello"; worksheet.Cells[1, 2].Value = "World"; package.SaveAs(new FileInfo(filePath)); } } } PDF文件操作 1. 读取PDF文件 在C#中,可以使用 iTextSharp 库来读取PDF文件。以下是一个示例代码: using System; using iTextSharp.text.pdf; class Program { static void Main() { string filePath = @"C:\example\pdffile.pdf"; using (PdfReader reader = new PdfReader(filePath)) { for (int i = 1; i <= reader.NumberOfPages; i++) { PdfDictionary page = reader.GetPage(i); string text = page.GetPageContent().ToString(); Console.WriteLine(text); } } } } 2. 写入PDF文件 同样可以使用 iTextSharp 库来写入PDF文件。以下是一个示例代码: using System; using iTextSharp.text; using iTextSharp.text.pdf; class Program { static void Main() { string filePath = @"C:\example\pdffile.pdf"; using (PdfWriter writer = PdfWriter.Create(new FileStream(filePath, FileMode.Create))) { Document document = new Document(); document.Add(new Paragraph("Hello, World!")); writer.Write(document); document.Close(); } } } 总结 本文介绍了C#中高效进行文本、Excel和PDF文件操作的技巧。通过使用相应的库,可以轻松实现文件的读写操作。在实际开发过程中,可以根据需要选择合适的库和操作方法。