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

c#
389
2023/11/27 21:40:20
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

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

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "data.txt"; // 文件路径

        // 使用StreamReader读取文件
        using (StreamReader sr = new StreamReader(filePath))
        {
            string line;
            while ((line = sr.ReadLine()) != null) // 逐行读取文件内容
            {
                Console.WriteLine(line);
            }
        }
    }
}

在上述代码中,首先创建了一个StreamReader对象,并将文件路径作为参数传递给它。然后,使用ReadLine()方法逐行读取文件内容,并将每行数据打印到控制台上。

请确保文件路径正确,并确保有读取文件的权限。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: C# Redis持久化方案选择何种