首页
学习
活动
专区
圈层
工具
发布

C#:从txt文件中读取数据

C# 从 txt 文件中读取数据

基础概念

在 C# 中,从文本文件(txt)读取数据是常见的 I/O 操作,涉及文件系统访问和数据处理。.NET 提供了多种类和方法来实现这一功能。

主要方法

1. 使用 File.ReadAllText 方法

最简单的方法,一次性读取整个文件内容为字符串。

代码语言:txt
复制
string filePath = @"C:\example\data.txt";
string content = File.ReadAllText(filePath);
Console.WriteLine(content);

优点

  • 代码简洁
  • 适合小文件

缺点

  • 大文件会占用大量内存

2. 使用 File.ReadAllLines 方法

读取所有行到字符串数组中,每行一个元素。

代码语言:txt
复制
string[] lines = File.ReadAllLines(filePath);
foreach (string line in lines)
{
    Console.WriteLine(line);
}

优点

  • 方便逐行处理
  • 适合结构化文本数据

3. 使用 StreamReader 类

逐行读取,内存效率高,适合大文件。

代码语言:txt
复制
using (StreamReader reader = new StreamReader(filePath))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}

优点

  • 内存效率高
  • 可以随时停止读取
  • 适合大文件处理

4. 使用 File.ReadLines (LINQ 方式)

延迟加载,适合需要 LINQ 查询的场景。

代码语言:txt
复制
IEnumerable<string> lines = File.ReadLines(filePath);
var filteredLines = lines.Where(line => line.Contains("keyword"));
foreach (string line in filteredLines)
{
    Console.WriteLine(line);
}

优点

  • 支持 LINQ 操作
  • 延迟执行,高效

常见问题及解决方案

1. 文件不存在异常

代码语言:txt
复制
if (File.Exists(filePath))
{
    // 读取文件
}
else
{
    Console.WriteLine("文件不存在");
}

2. 编码问题

指定正确的编码格式:

代码语言:txt
复制
string content = File.ReadAllText(filePath, Encoding.UTF8);

3. 大文件处理

使用 StreamReader 逐行读取,避免内存溢出。

4. 文件被占用

确保文件未被其他进程锁定,或使用 try-catch 处理异常。

应用场景

  1. 配置文件读取:读取应用程序配置
  2. 日志分析:处理日志文件
  3. 数据导入:从文本文件导入数据到数据库
  4. 批处理:执行基于文本文件的批处理操作

性能考虑

  • 小文件:使用 File.ReadAllText/ReadAllLines
  • 大文件:使用 StreamReader 逐行读取
  • 需要复杂查询:使用 File.ReadLines 配合 LINQ

完整示例

代码语言:txt
复制
using System;
using System.IO;
using System.Text;

class Program
{
    static void Main()
    {
        string filePath = @"C:\data\example.txt";
        
        try
        {
            // 方法1: 读取全部内容
            Console.WriteLine("--- 全部内容 ---");
            string allText = File.ReadAllText(filePath, Encoding.UTF8);
            Console.WriteLine(allText);
            
            // 方法2: 逐行读取
            Console.WriteLine("\n--- 逐行读取 ---");
            using (StreamReader reader = new StreamReader(filePath))
            {
                int lineNumber = 1;
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    Console.WriteLine($"{lineNumber}: {line}");
                    lineNumber++;
                }
            }
            
            // 方法3: 使用LINQ处理
            Console.WriteLine("\n--- 包含'a'的行 ---");
            var linesWithA = File.ReadLines(filePath)
                               .Where(l => l.Contains("a"));
            foreach (var line in linesWithA)
            {
                Console.WriteLine(line);
            }
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("文件未找到");
        }
        catch (IOException ex)
        {
            Console.WriteLine($"IO异常: {ex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"发生错误: {ex.Message}");
        }
    }
}

这个示例展示了三种常见的读取文本文件的方法,并包含了基本的错误处理。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的文章

领券