Redigera

Dela via


File.ReadLines Method

Definition

Reads the lines of a file.

Overloads

ReadLines(String, Encoding)

Read the lines of a file that has a specified encoding.

ReadLines(String)

Reads the lines of a file.

ReadLines(String, Encoding)

Source:
File.cs
Source:
File.cs
Source:
File.cs

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>
Public Shared Function ReadLines (path As String, encoding As Encoding) As IEnumerable(Of String)

Parameters

path
String

The file to read.

encoding
Encoding

The encoding that is applied to the contents of the file.

Returns

All the lines of the file, or the lines that are the result of a query.

Exceptions

.NET Framework and .NET Core versions older than 2.1: path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by the GetInvalidPathChars() method.

path is null.

path is invalid (for example, it is on an unmapped drive).

The file specified by path was not found.

An I/O error occurred while opening the file.

path exceeds the system-defined maximum length.

The caller does not have the required permission.

path specifies a file that is read-only.

-or-

This operation is not supported on the current platform.

-or-

path is a directory.

-or-

The caller does not have the required permission.

Remarks

Use this method to specify an encoding to use read the file.

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. Therefore, when you are working with very large files, ReadLines can be more efficient.

You can use the ReadLines method to do the following:

Applies to

ReadLines(String)

Source:
File.cs
Source:
File.cs
Source:
File.cs

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)

Parameters

path
String

The file to read.

Returns

All the lines of the file, or the lines that are the result of a query.

Exceptions

.NET Framework and .NET Core versions older than 2.1: path is a zero-length string, contains only white space, or contains one or more invalid characters defined by the GetInvalidPathChars() method.

path is null.

path is invalid (for example, it is on an unmapped drive).

The file specified by path was not found.

An I/O error occurred while opening the file.

path exceeds the system-defined maximum length.

The caller does not have the required permission.

path specifies a file that is read-only.

-or-

This operation is not supported on the current platform.

-or-

path is a directory.

-or-

The caller does not have the required permission.

Examples

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 line in File.ReadLines @"d:\data\episodes.txt" do
    if line.Contains "episode" && line.Contains "2006" then
        printfn $"{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

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

try
    // Set a variable to the My Documents path.
    let docPath =
        Environment.GetFolderPath Environment.SpecialFolder.MyDocuments

    let files =
        query {
            for file in Directory.EnumerateFiles(docPath, "*.txt", SearchOption.AllDirectories) do
            for line in File.ReadLines file do
            where (line.Contains "Microsoft")
            select {| File = file; Line = line |}
        }

    for f in files do
        printfn $"{f.File}\t{f.Line}"
    printfn $"{Seq.length files} files found."

with
| :? UnauthorizedAccessException as uAEx -> printfn $"{uAEx.Message}"
| :? PathTooLongException as pathEx -> printfn $"{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

Remarks

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. Therefore, when you are working with very large files, ReadLines can be more efficient.

You can use the ReadLines method to do the following:

This method uses UTF8 for the encoding value.

Applies to