File.ReadLines 方法

定義

讀取檔案的所有行。Reads the lines of a file.

多載

ReadLines(String)

讀取檔案的所有行。Reads the lines of a file.

ReadLines(String, Encoding)

讀取具有指定編碼方式的檔案所有行。Read the lines of a file that has a specified encoding.

ReadLines(String)

讀取檔案的所有行。Reads the lines of a file.

public:
 static System::Collections::Generic::IEnumerable<System::String ^> ^ ReadLines(System::String ^ path);
public static System.Collections.Generic.IEnumerable<string> ReadLines (string path);
static member ReadLines : string -> seq<string>
Public Shared Function ReadLines (path As String) As IEnumerable(Of String)

參數

path
String

要讀取的檔案。The file to read.

傳回

檔案的所有行,或查詢結果的各行。All the lines of the file, or the lines that are the result of a query.

例外狀況

path 為零長度字串、只包含空格或包含 GetInvalidPathChars() 方法所定義的一或多個無效字元。path is a zero-length string, contains only white space, or contains one or more invalid characters defined by the GetInvalidPathChars() method.

pathnullpath is null.

path 無效 (例如它位於未對應的磁碟機上)。path is invalid (for example, it is on an unmapped drive).

找不到 path 所指定的檔案。The file specified by path was not found.

開啟檔案時發生 I/O 錯誤。An I/O error occurred while opening the file.

path 超過系統定義的長度上限。path exceeds the system-defined maximum length.

呼叫端沒有必要的使用權限。The caller does not have the required permission.

path 指定唯讀的檔案。path specifies a file that is read-only.

-或--or- 這個作業在目前平台不受支援。This operation is not supported on the current platform.

-或--or- path 是目錄。path is a directory.

-或--or- 呼叫端沒有必要的使用權限。The caller does not have the required permission.

範例

下列範例會讀取檔案的行,以尋找包含指定之字串的行。The following example reads the lines of a file to find lines that contain specified strings.

foreach (string line in File.ReadLines(@"d:\data\episodes.txt"))
{
    if (line.Contains("episode") & line.Contains("2006"))
    {
        Console.WriteLine(line);
    }
}
For Each line As String In File.ReadLines("d:\data\episodes.txt")
    If line.Contains("episode") And line.Contains("2006") Then
        Console.WriteLine(line)
    End If
Next line

下列範例會在 LINQ 查詢中使用 ReadLines 方法,以列舉副檔名為 .txt 之檔案的所有目錄,並讀取檔案的每一行,並在包含字串 "Microsoft" 時顯示該行。The following example uses the ReadLines method in a LINQ query that enumerates all directories for files that have a .txt extension, reads each line of the file, and displays the line if it contains the string "Microsoft".

using System;
using System.IO;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        try
        {
            // Set a variable to the My Documents path.
            string docPath =
            Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            var files = from file in Directory.EnumerateFiles(docPath, "*.txt", SearchOption.AllDirectories)
                        from line in File.ReadLines(file)
                        where line.Contains("Microsoft")
                        select new
                        {
                            File = file,
                            Line = line
                        };

            foreach (var f in files)
            {
                Console.WriteLine($"{f.File}\t{f.Line}");
            }
            Console.WriteLine($"{files.Count().ToString()} files found.");
        }
        catch (UnauthorizedAccessException uAEx)
        {
            Console.WriteLine(uAEx.Message);
        }
        catch (PathTooLongException pathEx)
        {
            Console.WriteLine(pathEx.Message);
        }
    }
}
Imports System.IO
Imports System.Xml.Linq

Module Module1

    Sub Main()
        Try
            Dim docPath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
            Dim files = From chkFile In Directory.EnumerateFiles(docPath, "*.txt", SearchOption.AllDirectories)
                        From line In File.ReadLines(chkFile)
                        Where line.Contains("Microsoft")
                        Select New With {.curFile = chkFile, .curLine = line}

            For Each f In files
                Console.WriteLine($"{f.File}\t{f.Line}")
            Next
            Console.WriteLine($"{files.Count} files found.")
        Catch uAEx As UnauthorizedAccessException
            Console.WriteLine(uAEx.Message)
        Catch pathEx As PathTooLongException
            Console.WriteLine(pathEx.Message)
        End Try
    End Sub
End Module

備註

ReadLinesReadAllLines 方法的差異如下:當您使用 ReadLines時,您可以在傳回整個集合之前,開始列舉字串的集合;當您使用 ReadAllLines時,您必須等候整個字串陣列傳回,然後才能存取陣列。The ReadLines and ReadAllLines methods differ as follows: When you use ReadLines, you can start enumerating the collection of strings before the whole collection is returned; when you use ReadAllLines, you must wait for the whole array of strings be returned before you can access the array. 因此,當您處理非常大的檔案時,ReadLines 可能會更有效率。Therefore, when you are working with very large files, ReadLines can be more efficient.

您可以使用 ReadLines 方法來執行下列動作:You can use the ReadLines method to do the following:

這個方法會使用 UTF8 做為編碼值。This method uses UTF8 for the encoding value.

ReadLines(String, Encoding)

讀取具有指定編碼方式的檔案所有行。Read the lines of a file that has a specified encoding.

public:
 static System::Collections::Generic::IEnumerable<System::String ^> ^ ReadLines(System::String ^ path, System::Text::Encoding ^ encoding);
public static System.Collections.Generic.IEnumerable<string> ReadLines (string path, System.Text.Encoding encoding);
static member ReadLines : string * System.Text.Encoding -> seq<string>

參數

path
String

要讀取的檔案。The file to read.

encoding
Encoding

套用至檔案內容的編碼方式。The encoding that is applied to the contents of the file.

傳回

檔案的所有行,或查詢結果的各行。All the lines of the file, or the lines that are the result of a query.

例外狀況

path 為零長度字串,只包含空格,或包含一或多個由 GetInvalidPathChars() 方法所定義的無效字元。path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by the GetInvalidPathChars() method.

pathnullpath is null.

path 無效 (例如它位於未對應的磁碟機上)。path is invalid (for example, it is on an unmapped drive).

找不到 path 所指定的檔案。The file specified by path was not found.

開啟檔案時發生 I/O 錯誤。An I/O error occurred while opening the file.

path 超過系統定義的長度上限。path exceeds the system-defined maximum length.

呼叫端沒有必要的使用權限。The caller does not have the required permission.

path 指定唯讀的檔案。path specifies a file that is read-only.

-或--or- 這個作業在目前平台不受支援。This operation is not supported on the current platform.

-或--or- path 是目錄。path is a directory.

-或--or- 呼叫端沒有必要的使用權限。The caller does not have the required permission.

備註

使用此方法來指定要用來讀取檔案的編碼方式。Use this method to specify an encoding to use read the file.

ReadLinesReadAllLines 方法的差異如下:當您使用 ReadLines時,您可以在傳回整個集合之前,開始列舉字串的集合。The ReadLines and ReadAllLines methods differ as follows: When you use ReadLines, you can start enumerating the collection of strings before the whole collection is returned. 當您使用 ReadAllLines時,您必須等候整個字串陣列傳回,然後才能存取陣列。When you use ReadAllLines, you must wait for the whole array of strings be returned before you can access the array. 因此,當您處理非常大的檔案時,ReadLines 可能會更有效率。Therefore, when you are working with very large files, ReadLines can be more efficient.

您可以使用 ReadLines 方法來執行下列動作:You can use the ReadLines method to do the following:

適用於