System.IO.File.ReadAllLines 方法 (String, Encoding)

方法描述

打开一个文件,使用指定的编码读取文件的所有行,然后关闭该文件。

语法定义(C# System.IO.File.ReadAllLines 方法 (String, Encoding) 的用法)

public static string[] ReadAllLines(
	string path,
	Encoding encoding
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
path System-String 要打开以进行读取的文件。
encoding System-Text-Encoding 应用到文件内容的编码。
返回值 System.String[] 包含文件所有行的字符串数组。

提示和注释

此方法打开一个文件,读取文件的每一行,然后将每一行添加为字符串数组的一个元素。 然后它关闭文件。 根据定义,一行就是一个后面跟有下列符号的字符序列:回车符(“\r”)、换行符(“\n”)或回车符后紧跟一个换行符。 所产生的字符串不包含终止回车符和/或换行符。

此方法尝试根据现存的字节顺序标记来自动检测文件的编码。 可检测到编码格式 UTF-8 和 UTF-32(包括 big-endian 和 little-endian)。

System.IO.File.ReadAllLines 方法 (String, Encoding)例子

在此示例中,如果文件尚不存在,则创建一个文件,并向其中添加文本。

using System;
using System.IO;
using System.Text;

class Test
{
    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";

        // This text is added only once to the file.
        if (!File.Exists(path))
        {
            // Create a file to write to.
            string[] createText = { "Hello", "And", "Welcome" };
            File.WriteAllLines(path, createText, Encoding.UTF8);
        }

        // This text is always added, making the file longer over time
        // if it is not deleted.
        string appendText = "This is extra text" + Environment.NewLine;
        File.AppendAllText(path, appendText, Encoding.UTF8);

        // Open the file to read from.
        string[] readText = File.ReadAllLines(path, Encoding.UTF8);
        foreach (string s in readText)
        {
            Console.WriteLine(s);
        }
    }
}

异常

异常 异常描述
ArgumentException path 是一个零长度字符串,仅包含空白或者包含一个或多个由 InvalidPathChars 定义的无效字符。
ArgumentNullException path 为 null。
PathTooLongException 指定的路径、文件名或者两者都超出了系统定义的最大长度。 例如,在基于 Windows 的平台上,路径必须小于 248 个字符,文件名必须小于 260 个字符。
DirectoryNotFoundException 指定的路径无效(例如,它位于未映射的驱动器上)。
IOException 打开文件时发生了 I/O 错误。
UnauthorizedAccessException
  • path 指定了一个只读文件。
  • 在当前平台上不支持此操作。
  • path 指定了一个目录。
  • 调用方没有所要求的权限。
FileNotFoundException 未找到 path 中指定的文件。
NotSupportedException path 的格式无效。
SecurityException 调用方没有所要求的权限。

命名空间

namespace: System.IO

程序集: mscorlib(在 mscorlib.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。