Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Reading Files Using File Methods | Data Structures & File Handling
C# Object-Oriented Structures

bookReading Files Using File Methods

メニューを表示するにはスワイプしてください

There are two additional methods of reading files which are significantly shorter in terms of syntax.

Consider a file called "text.txt" which has the following content:

text.txt

text.txt

copy
123
First Second Third

File.ReadAllText Method

You can use the File.ReadAllText to retrieve all the text from a file at once:

index.cs

index.cs

copy
12
string text = File.ReadAllText("C:/Users/Admin/Desktop/text.txt"); Console.WriteLine(text);

Output:

First
Second
Third

File.ReadAllLines Method

The File.ReadAllLines method retrieves all text as well, however it returns data in the form of a string array where each element is an individual line from the file:

index.cs

index.cs

copy
12345
string[] lines = File.ReadAllLines("C:/Users/Admin/Desktop/text.txt"); foreach(string line in lines) { Console.WriteLine(line); }

Output:

First
Second
Third

The difference between StreamReader and the File methods is that with StreamReader you have more control over how many lines and which lines we want to read from the file. For example if there's a file with over a million lines and you want to retrieve only the first 1000 lines or some specific lines from the middle of the file then in that case using StreamReader will be much more efficient.

question mark

What is the most efficient way of reading half of a file's content in case of large files?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  7

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 1.  7
some-alt