File.ReadAllLines 方法 (String)
打开一个文本文件,读取文件的所有行,然后关闭该文件。
命名空间: System.IO
程序集: mscorlib(在 mscorlib.dll 中)
| 异常类型 | 条件 |
|---|---|
|
path 是一个零长度字符串,仅包含空白或者包含一个或多个由 InvalidPathChars 定义的无效字符。 |
|
|
path 为 空引用(在 Visual Basic 中为 Nothing)。 |
|
|
指定的路径、文件名或者两者都超出了系统定义的最大长度。例如,在基于 Windows 的平台上,路径必须小于 248 个字符,文件名必须小于 260 个字符。 |
|
|
指定的路径无效(例如,它位于未映射的驱动器上)。 |
|
|
打开文件时发生了 I/O 错误。 |
|
|
path 指定了一个只读文件。 - 或 - 在当前平台上不支持此操作。 - 或 - path 指定了一个目录。 - 或 - 调用方没有所要求的权限。 |
|
|
未找到 path 中指定的文件。 |
|
|
path 的格式无效。 |
|
|
调用方没有所要求的权限。 |
下面的代码示例演示如何使用 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); } } }
- FileIOPermission 从文件或目录中读取的访问权限。关联的枚举:FileIOPermissionAccess.Read。

浙公网安备 33010602011771号