File.ReadAllLines是C#中一个用于读取文本文件内容的静态方法。它可以将文本文件中的所有行读取到一个字符串数组中,方便我们对文本内容进行处理分析。
以下是File.ReadAllLines的完整使用攻略:
作用
File.ReadAllLines方法的作用是读取指定文本文件的所有行,并将它们存储在一个字符串数组中供用户使用。
语法
public static string[] ReadAllLines(string path);
public static string[] ReadAllLines(string path, Encoding encoding);
参数
- path:要读取的文件的路径
- encoding:读取文件所使用的编码格式
返回值
返回一个包含指定文件中所有行的字符串数组。
示例1:读取本地文件
以下代码演示了如何使用File.ReadAllLines方法读取本地文件,将其内容打印到控制台上:
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
try
{
string[] lines = File.ReadAllLines(@"C:\Example\test.txt");
foreach (string line in lines)
{
Console.WriteLine(line);
}
}
catch (Exception ex)
{
Console.WriteLine("读取文件出错:" + ex.Message);
}
}
}
这个示例中,我们假设文本文件位于C:\Example\test.txt。如果文件存在,程序将读取其中所有行并打印到控制台上;如果文件不存在或读取失败,程序将抛出异常并捕获错误消息。
示例2:读取Web文件
File.ReadAllLines方法不仅可以读取本地文件,还可以读取Web上的文件。以下代码演示了如何使用File.ReadAllLines方法从指定的URL地址读取文本文件内容:
using System;
using System.IO;
using System.Net;
class Program
{
static void Main(string[] args)
{
try
{
string url = "http://example.com/test.txt";
WebClient client = new WebClient();
Stream stream = client.OpenRead(url);
StreamReader reader = new StreamReader(stream);
string[] lines = reader.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in lines)
{
Console.WriteLine(line);
}
}
catch (Exception ex)
{
Console.WriteLine("读取网页出错:" + ex.Message);
}
}
}
这个示例中,我们使用WebClient类读取指定网址上的文本文件,然后将语句拆分为字符串数组并逐行输出。该实例类似于我们在前一个示例中所执行的操作,只是没有读取本地文件。