File.ReadLines 메서드
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
파일의 줄을 읽습니다.
오버로드
| Name | Description |
|---|---|
| ReadLines(String, Encoding) |
지정된 인코딩이 있는 파일의 줄을 읽습니다. |
| ReadLines(String) |
파일의 줄을 읽습니다. |
ReadLines(String, Encoding)
- Source:
- File.cs
- Source:
- File.cs
- Source:
- File.cs
- Source:
- File.cs
- Source:
- File.cs
지정된 인코딩이 있는 파일의 줄을 읽습니다.
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)
매개 변수
- path
- String
읽을 파일입니다.
- encoding
- Encoding
파일 내용에 적용되는 인코딩입니다.
반품
파일의 모든 줄 또는 쿼리의 결과인 줄입니다.
예외
.NET Framework 및 .NET Core 버전 2.1 이전: path 길이가 0인 문자열이거나, 공백만 포함하거나, GetInvalidPathChars() 메서드에 정의된 하나 이상의 잘못된 문자를 포함합니다.
path은 null입니다.
path 가 잘못되었습니다(예: 매핑되지 않은 드라이브에 있는 경우).
지정한 path 파일을 찾을 수 없습니다.
파일을 여는 동안 I/O 오류가 발생했습니다.
path 가 시스템 정의 최대 길이를 초과합니다.
호출자에게 필요한 권한이 없습니다.
path 는 읽기 전용인 파일을 지정합니다.
-또는-
이 작업은 현재 플랫폼에서 지원되지 않습니다.
-또는-
path 는 디렉터리입니다.
-또는-
호출자에게 필요한 권한이 없습니다.
설명
이 메서드를 사용하여 파일 읽기를 사용할 인코딩을 지정합니다.
메서드 및 ReadAllLines 메서드는 ReadLines 다음과 같이 다릅니다. 사용하는 ReadLines경우 전체 컬렉션이 반환되기 전에 문자열 컬렉션을 열거할 수 있습니다. 사용하는 ReadAllLines경우 배열에 액세스하기 전에 전체 문자열 배열이 반환될 때까지 기다려야 합니다. 따라서 매우 큰 파일 ReadLines 로 작업하는 경우 더 효율적일 수 있습니다.
이 메서드를 ReadLines 사용하여 다음을 수행할 수 있습니다.
- 파일에서 LINQ to Objects 쿼리를 수행하여 필터링된 줄 집합을 가져옵니다.
- 반환된 줄 컬렉션을 메서드를 사용하여 파일에 File.WriteAllLines(String, IEnumerable<String>, Encoding) 쓰거나 메서드를 사용하여 기존 파일에 File.AppendAllLines(String, IEnumerable<String>, Encoding) 추가합니다.
- 해당 생성자(예: a 또는 a)에 대한 문자열 컬렉션을 사용하는 IEnumerable<T> 컬렉션의 즉시 채워진 인스턴스를 IList<T>Queue<T>만듭니다.
줄은 캐리지 리턴('\r'), 줄 바꿈('\n'), 줄 바꿈 바로 뒤에 오는 캐리지 리턴 또는 파일 또는 스트림의 끝으로 끝나는 문자 시퀀스로 정의됩니다. 파일이 줄 바꿈 시퀀스로 끝나는 경우 빈 줄이 추가로 반환되지 않습니다. 예를 들어 포함하는 "line1\nline2\n" 파일은 포함하는 파일과 동일한 두 줄("line1" 및 "line2")을 생성합니다 "line1\nline2".
적용 대상
ReadLines(String)
- Source:
- File.cs
- Source:
- File.cs
- Source:
- File.cs
- Source:
- File.cs
- Source:
- File.cs
파일의 줄을 읽습니다.
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
읽을 파일입니다.
반품
파일의 모든 줄 또는 쿼리의 결과인 줄입니다.
예외
.NET Framework 및 .NET Core 버전이 2.1보다 오래된 경우: path 길이가 0인 문자열이거나, 공백만 포함하거나, GetInvalidPathChars() 메서드에서 정의한 하나 이상의 잘못된 문자를 포함합니다.
path은 null입니다.
path 가 잘못되었습니다(예: 매핑되지 않은 드라이브에 있는 경우).
지정한 path 파일을 찾을 수 없습니다.
파일을 여는 동안 I/O 오류가 발생했습니다.
path 가 시스템 정의 최대 길이를 초과합니다.
호출자에게 필요한 권한이 없습니다.
path 는 읽기 전용인 파일을 지정합니다.
-또는-
이 작업은 현재 플랫폼에서 지원되지 않습니다.
-또는-
path 는 디렉터리입니다.
-또는-
호출자에게 필요한 권한이 없습니다.
예제
다음 예제에서는 파일의 줄을 읽어 지정된 문자열이 포함된 줄을 찾습니다.
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
다음 예제에서는 .txt 확장명이 있는 파일의 모든 디렉터리를 열거하고 파일의 각 줄을 읽고 문자열 "Microsoft"이 포함된 경우 줄을 표시하는 LINQ 쿼리에서 ReadLines 메서드를 사용합니다.
using System;
using System.IO;
using System.Linq;
partial class Example2
{
static void SearchOptionExample()
{
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()} 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
Partial Class Example2
Shared Sub SearchOptionExample()
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.curFile}\t{f.curLine}")
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 Class
설명
메서드와 ReadAllLines 메서드는 ReadLines 다음과 같습니다. 사용할 ReadLines때 전체 컬렉션이 반환되기 전에 문자열 컬렉션을 열거할 수 있습니다. 사용할 ReadAllLines때는 전체 문자열 배열이 반환될 때까지 기다려야 배열에 액세스할 수 있습니다. 따라서 매우 큰 파일 ReadLines 로 작업하는 경우 더 효율적일 수 있습니다.
이 메서드를 ReadLines 사용하여 다음을 수행할 수 있습니다.
- 파일에서 LINQ to Objects 쿼리를 수행하여 필터링된 줄 집합을 가져옵니다.
- 반환된 줄 컬렉션을 메서드를 사용하여 파일에 File.WriteAllLines(String, IEnumerable<String>) 쓰거나 메서드를 사용하여 기존 파일에 File.AppendAllLines(String, IEnumerable<String>) 추가합니다.
- 해당 생성자(예: a 또는 a)에 대한 문자열 컬렉션을 사용하는 IEnumerable<T> 컬렉션의 즉시 채워진 인스턴스를 IList<T>Queue<T>만듭니다.
이 메서드는 인코딩 값에 사용합니다 UTF8 .
줄은 문자 시퀀스 뒤에 캐리지 리턴('\r'), 줄 바꿈('\n') 또는 줄 바꿈 바로 뒤에 캐리지 리턴으로 정의되거나 줄 바꿈 없이 끝나는 경우 파일 또는 스트림의 최종 문자 시퀀스로 정의됩니다. 파일이 줄 바꿈 시퀀스로 끝나는 경우 빈 줄이 추가로 반환되지 않습니다. 예를 들어 포함하는 "line1\nline2\n" 파일은 포함하는 파일과 동일한 두 줄("line1" 및 "line2")을 생성합니다 "line1\nline2".