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

   2025-02-13 8590
核心提示:在C#中,可以使用StreamReader类来读取文件中的数据。以下是一个简单的示例代码,演示如何从文件中读取数据:using System;using

在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()方法逐行读取文件内容,并将每行数据打印到控制台上。

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

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言