How to Open a File in C and Read It
In few previous articles, I have explained how we can read JSON information in C# and how to read excel file in C#, now in this article, I have provided code sample using console application to show how to read a text file in C# line past line or reading entire text file as a string in one by go using C#.
Let'southward a look at each of the example code, one in which text file is read and converted into string, i.e, using System.IO.ReadAllText()
and another is reading text file line by line using Arrangement.IO.ReadAllLines()
which returns array of line, and we can loop that array to print each line of text file.
Read File in .NET Framework iv.5 Panel application
Reading file in C# line by line
In this instance, we will read a text file line by line using System.IO.ReadALLLines() in panel awarding.
Then, if yous are new to C# or Visual Studio, you can create a new Console application by opening Visual Studio, navigating to "New"-> "Project" -> Select "Windows Classic" from left-pane and "Panel app (Windows Awarding)"-> Give a name to your projection "ReadInCSharp" and click "OK"
At present, inside Programme.cs, nosotros will write our lawmaking
using Organization; using System.IO; namespace ReadInCSharp { class Program { static void Main(cord[] args) { //file in deejay var FileUrl = @"D:\testFile.txt"; //file lines string[] lines = File.ReadAllLines(FileUrl); //loop through each file line foreach (string line in lines) { Console.WriteLine(line); } } } }
Output:
This is test file. To Read text file in C# Sample.
In the to a higher place, code nosotros are using foreach loop to read all lines of an string assortment.
Reading text in C# all line at once
Let'southward take a await at C# code to read all lines at in one case of a text file.
using System; using Arrangement.IO; namespace ReadInCSharp { class Program { static void Main(string[] args) { //file in disk var FileUrl = @"D:\testFile.txt"; // Read entire text file content in one string string text = File.ReadAllText(FileUrl); Panel.WriteLine(text); } } }
Output:
This is test file. To Read text file in C# Sample.
Reading Text file using StreamReader
There is i more than way to read lines of a text file in C#, which is using StreamReader
.
StreamReader
class implements a TextReader that reads characters from a byte stream in a particular encoding.
using Organisation; using Arrangement.IO; namespace ReadInCSharp { class Program { static void Master(cord[] args) { //file in disk var FileUrl = @"D:\testFile.txt"; attempt { // Create an instance of StreamReader to read from a file. // The using argument likewise closes the StreamReader. using (StreamReader sr = new StreamReader(FileUrl)) { string line; //read the line by line and print each line while ((line = sr.ReadLine()) != goose egg) { Panel.WriteLine(line); } } } catch (Exception due east) { // Something went incorrect. Console.WriteLine("The file could not be read:"); //print error message Panel.WriteLine(e.Bulletin); } } } }
Output is same as above, in the abovde code, we are using StreamReader example to read text from file.
As you can see in the in a higher place code, we are feeding the File url to "StreamReader
" class object and then we are reading file line by line using sr.ReadLine(), which gives u.s.a. one line at a time from text file, and so using Panel.WriteLine()
, we are printing the value of that line panel application.
Read File in .NET Core Console application
In the above example, we were reading file using .NET framework, but you tin too read files using 'StreamReader' in .Net Cadre, hither is the working example.
Before, I show you instance, I have created a new console awarding using .Internet Core in Visual Studio 2019 (Open Visual Studio -> Click on Create new project -> Select "Console App (.Net Cadre)" from templates -> Click "Side by side", requite your project a name "ReadFileInNetCore" -> Click "Create")
Because you have text file at location "D:\testFile.txt", you can apply the beneath C# Lawmaking in .NET Core to read text file line by line.
using Organisation; using System.IO; namespace ReadFileInNetCore { grade Plan { static void Main(string[] args) { FileStream fileStream = new FileStream(@"D:\testFile.txt", FileMode.Open up); //read file line by line using StreamReader using (StreamReader reader = new StreamReader(fileStream)) { string line = ""; while ((line = reader.ReadLine()) != null) { //impress line Console.WriteLine(line); } } Console.WriteLine("Press any key to continue"); Console.ReadKey(); } } }
If you will see the in a higher place lawmaking, you will notice, in that location isn't any departure in C# Code, when working with .NET 4.five or .NET Core.
Output:
To read all files at once, you can apply "ReadAllText" every bit mentioned for .NET Framework "Organisation.IO.File.ReadAllText("YourFileLocatio.txt");
"
Annotation: If you are working with .Net Core iii and working with web-awarding, and you want to read file from wwwroot location, y'all can locate "wwwroot" binder as below:
individual readonly IWebHostEnvironment _webHostEnvironment; public YourController (IWebHostEnvironment webHostEnvironment) { _webHostEnvironment= webHostEnvironment; } public IActionResult Index() { string webRootPath = _webHostEnvironment.WebRootPath; cord contentRootPath = _webHostEnvironment.ContentRootPath; string path =""; path = Path.Combine(webRootPath , "yourFolder"); //or path = Path.Combine(contentRootPath , "wwwroot" ,"yourFolder" ); return View(); }
You may as well like to read:
Read PDF file in C# using iTextSharp
Source: https://qawithexperts.com/article/c-sharp/read-file-in-c-text-file-example-using-console-application/262
0 Response to "How to Open a File in C and Read It"
Post a Comment