优秀的编程知识分享平台

网站首页 > 技术文章 正文

c#.Net.NetCore面试(四十四)c#/net/netcore读取文件

nanyue 2024-07-19 23:57:20 技术文章 21 ℃

在c#、.NET或.NET Core中读取文件的内容。(c#方法很多,只介绍都能用的)

使用StreamReader

StreamReader类是用于从文本文件中读取行的常用方法。

using System;  
using System.IO;  
  
class Program  
{  
    static void Main()  
    {  
        string filePath = "path/to/your/file.txt"; // 替换为你的文件路径  
  
        try  
        {  
            // 打开文件并创建一个StreamReader对象  
            using (StreamReader sr = new StreamReader(filePath))  
            {  
                string line;  
  
                // 读取并显示文件的行,直到文件的末尾  
                while ((line = sr.ReadLine()) != null)  
                {  
                    Console.WriteLine(line);  
                }  
            }  
        }  
        catch (Exception e)  
        {  
            Console.WriteLine("文件读取错误:");  
            Console.WriteLine(e.Message);  
        }  
    }  
}

使用File.ReadAllText

如果你想要一次性读取整个文件的内容,可以使用File.ReadAllText方法。

using System;  
using System.IO;  
  
class Program  
{  
    static void Main()  
    {  
        string filePath = "path/to/your/file.txt"; // 替换为你的文件路径  
  
        try  
        {  
            // 读取整个文件的内容为一个字符串  
            string content = File.ReadAllText(filePath);  
            Console.WriteLine(content);  
        }  
        catch (Exception e)  
        {  
            Console.WriteLine("文件读取错误:");  
            Console.WriteLine(e.Message);  
        }  
    }  
}

使用File.ReadLines

如果你想要按行读取大型文件,但又不想一次性加载整个文件到内存中,可以使用File.ReadLines方法。这个方法返回一个按行读取文件的字符串集合

using System;  
using System.IO;  
using System.Linq; // 需要引入Linq命名空间来使用Select等扩展方法(尽管在这个例子中没有用到)  
  
class Program  
{  
    static void Main()  
    {  
        string filePath = "path/to/your/file.txt"; // 替换为你的文件路径  
  
        try  
        {  
            // 按行读取文件的内容  
            foreach (string line in File.ReadLines(filePath))  
            {  
                Console.WriteLine(line);  
            }  
        }  
        catch (Exception e)  
        {  
            Console.WriteLine("文件读取错误:");  
            Console.WriteLine(e.Message);  
        }  
    }  
}

确保你的项目引用了必要的命名空间,通常是SystemSystem.IO。此外,请记得处理可能出现的异常,比如文件不存在、没有读取权限等。在上面的示例中,我使用了try-catch语句来捕获和处理可能出现的异常。

最近发表
标签列表