How to Read from a Text File in C#? -- C# -- System.IO.StreamReader
How to Read from a Text File in C#? -- C# -- System.IO.StreamReader
[Ans]
using System.IO.StreamReader()
[Syntax]
StreamReader StreamReader(string fileName);
where fileName is the name of file that you read
[NOTE]
Great Importance!!! Please pay a lot attention!!!
(1)
Compiler reads file under subfiolder of the path \bin\Debug\netcoreapp3.1 in your project.
When you use StreamReader, the argument will be given as
<yourProject>\bin\Debug\netcoreapp3.1\<fileName>
e.g.
When I create a new C# project with project name StreamReader_All in the path C:\Users\jayw7\OneDrive\桌面\CSharp\StreamReader .
I should write
C:\Users\jayw7\OneDrive\桌面\CSharp\StreamReader\StreamReader_All\StreamReader_All\bin\Debug\netcoreapp3.1
(2)
In C#, "\" means escape character.
If you would like to present a directory, you must use "\\" instead of "\" or add "@" before your directory.
How to read all lines from text file in C#?
step1:
read file from text file with StreamReader().
step2:
read a line from StreamReader with ReadToEnd() method.
example code:
using (StreamReader sr=new StreamReader("Invoke_InvokeRepeating.txt"))
{
string s = "";
s = sr.ReadToEnd();
Console.WriteLine(s);
}
How to read a line from text file in C#?
step1:
read file from text file with StreamReader().
step2:
read a line from StreamReader with ReadLine() method.
example code:
using (StreamReader sr=new StreamReader("Invoke_InvokeRepeating.txt"))
{
string line = "";
line = sr.ReadLine();
int index = 1;
while(line!=null)
{
Console.WriteLine(index + "th line:" +line);
index += 1;
line = sr.ReadLine();
}
}
[Useful Tips]
I recommend you that close the StreamReader after using it.
And When StreamReader is declared in using keyword, system will automatically close it after using block ending.
Comments
Post a Comment