📌  相关文章
📜  C#中的File.ReadAllLines(String)方法与示例

📅  最后修改于: 2021-05-29 15:22:32             🧑  作者: Mango

File.ReadAllLines(String)是一个内置的File类方法,该方法用于打开文本文件,然后将文件的所有行读取到字符串数组中,然后关闭文件。
句法:

public static string[] ReadAllLines (string path);

参数:该函数接受如下所示的参数:

例外情况:

  • ArgumentException:路径是长度为零的字符串,仅包含空格,或者由InvalidPathChars定义的一个或多个无效字符。
  • ArgumentNullException:路径为null。
  • PathTooLongException:指定的路径,文件名或两者都超过系统定义的最大长度。
  • DirectoryNotFoundException:指定的路径无效。
  • IOException:打开文件时发生I / O错误。
  • UnauthorizedAccessException:路径指定了一个只读文件。或当前平台不支持此操作。或路径指定目录。或呼叫者没有所需的权限。
  • FileNotFoundException:找不到在路径中指定的文件。
  • NotSupportedException:路径格式无效。
  • SecurityException:调用者没有所需的权限。

返回值:返回包含文件所有行的字符串数组。
下面是说明File.ReadAllLines(String)方法的程序。
程序1:最初,将创建一个文件file.txt ,其内容如下所示-

file.txt

C#
// C# program to illustrate the usage
// of File.ReadAllLines(String) method
  
// Using System, System.IO and
// System.Text namespaces
using System;
using System.IO;
using System.Text;
  
class GFG {
    public static void Main()
    {
        // Specifying a file
        string path = @"file.txt";
  
        // Calling the ReadAllLines() function
        string[] readText = File.ReadAllLines(path);
        foreach(string s in readText)
        {
            // Printing the string array containing
            // all lines of the file.
            Console.WriteLine(s);
        }
    }
}


C#
// C# program to illustrate the usage
// of File.ReadAllLines(String) method
  
// Using System, System.IO and
// System.Text namespaces
using System;
using System.IO;
using System.Text;
  
class GFG {
    public static void Main()
    {
        // Specifying a file
        string path = @"file.txt";
  
        // Adding below contents to the file
        string[] createText = { "GFG is a CS portal." };
        File.WriteAllLines(path, createText);
  
        // Calling the ReadAllLines() function
        string[] readText = File.ReadAllLines(path);
        foreach(string s in readText)
        {
            // Printing the string array containing
            // all lines of the file.
            Console.WriteLine(s);
        }
    }
}


输出:

GFG
Geeks
GeeksforGeeks

程序2:最初没有创建文件。下面的代码本身创建带有一些指定内容的文件file.txt

C#

// C# program to illustrate the usage
// of File.ReadAllLines(String) method
  
// Using System, System.IO and
// System.Text namespaces
using System;
using System.IO;
using System.Text;
  
class GFG {
    public static void Main()
    {
        // Specifying a file
        string path = @"file.txt";
  
        // Adding below contents to the file
        string[] createText = { "GFG is a CS portal." };
        File.WriteAllLines(path, createText);
  
        // Calling the ReadAllLines() function
        string[] readText = File.ReadAllLines(path);
        foreach(string s in readText)
        {
            // Printing the string array containing
            // all lines of the file.
            Console.WriteLine(s);
        }
    }
}

输出:

GFG is a CS portal.