c#

c#怎么读取文件中的数据

小亿
92
2023-11-24 01:39:35
栏目: 编程语言

在C#中,可以使用StreamReader类来读取文件中的数据。下面是一个示例代码:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        try
        {
            // 指定文件路径
            string filePath = "path/to/your/file.txt";

            // 创建StreamReader对象,并将文件路径传递给构造函数
            using (StreamReader sr = new StreamReader(filePath))
            {
                string line;

                // 逐行读取文件内容
                while ((line = sr.ReadLine()) != null)
                {
                    // 处理每一行的数据
                    Console.WriteLine(line);
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("读取文件时发生错误: " + e.Message);
        }
    }
}

在上面的示例中,我们首先通过指定文件路径来创建一个StreamReader对象,然后使用sr.ReadLine()方法逐行读取文件内容,直到读取到文件末尾。每次读取一行后,可以根据需要进行相应的处理。

0
看了该问题的人还看了