Now let's create a .net core console application and add some code to read the text file content or data using LINQ in c#.net.
string folderPath = "D:\\DemoRepo\\Myfolder";
string fileName = "textfile1.txt";
if (Path.Exists(folderPath))
{
string filePath = string.Format("{0}\\{1}", folderPath, fileName);
if (File.Exists(filePath))
{
try
{
var textData = from d in File.ReadAllLines(filePath)
select d;
Console.WriteLine("FILE CONTENT");
foreach (var line in textData)
{
Console.WriteLine(line);
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
else
{
Console.WriteLine("Sorry file not found....");
}
}
In above code I have declared a variable named as folderPath and second variable named as fileName. After declaring the variables, I have validated whether the provided directory path exists or not, if folder does not exist you can create a folder. If it exists, I have used string.Format() to concatenate the string to get the complete path of the files. Ones we got the file path I have validated whether the file exists or not. If you try to read a file which does not exists without validating the file existence you will get an error as shown below.
Error!
Could not find file 'D:\DemoRepo\Myfolder\textfile1q.txt'.
Now we will user File.ReadAllLines() to read the file by passing the file path as a parameter. Here I have used LINQ query to read all data in the text file. Here one thing we need to look that by using LINQ you are getting the collection, and, in this collection, you can apply your condition to filter the data. Let's display the file content. Please check the below code to read and display the file content.
var textData = from d in File.ReadAllLines(filePath)
select d;
Console.WriteLine("FILE CONTENT");
foreach (var line in textData)
{
Console.WriteLine(line);
}
Here you can see we have received three lines of data, which is available in the textt file. Now lets press F5 and check the final output.
var textData = from d in File.ReadAllLines(filePath)
where !d.Contains("text 2")
select d;
Check the highlighted code. I have applied the condition don't include the text which i not having "text 2". Now run the code and check the output.