File.ReadAllLines 方法 (String)

打开一个文本文件,读取文件的所有行,然后关闭该文件。

命名空间: System.IO
程序集: mscorlib(在 mscorlib.dll 中)

 
public static string[] ReadAllLines (
	string path
)
 
public static String[] ReadAllLines (
	String path
)
 
public static function ReadAllLines (
	path : String
) : String[]
 
不适用。

 

参数

path

要打开以进行读取的文件。

 

 

返回值

包含文件所有行的字符串数组。
异常类型条件

ArgumentException

path 是一个零长度字符串,仅包含空白或者包含一个或多个由 InvalidPathChars 定义的无效字符。

ArgumentNullException

path 为 空引用(在 Visual Basic 中为 Nothing)。

PathTooLongException

指定的路径、文件名或者两者都超出了系统定义的最大长度。例如,在基于 Windows 的平台上,路径必须小于 248 个字符,文件名必须小于 260 个字符。

DirectoryNotFoundException

指定的路径无效(例如,它位于未映射的驱动器上)。

IOException

打开文件时发生了 I/O 错误。

UnauthorizedAccessException

path 指定了一个只读文件。

- 或 -

在当前平台上不支持此操作。

- 或 -

path 指定了一个目录。

- 或 -

调用方没有所要求的权限。

FileNotFoundException

未找到 path 中指定的文件。

NotSupportedException

path 的格式无效。

SecurityException

调用方没有所要求的权限。

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

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

下面的代码示例演示如何使用 ReadAllLines 方法显示文件的内容。在此示例中,如果文件尚不存在,则创建一个文件,并向其中添加文本。

 
using System;
using System.IO;
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);
        }

        // 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);

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

posted @ 2013-09-15 21:01  邹邹  Views(1917)  Comments(0)    收藏  举报