Reading and writing files are two of the most common tasks in the world of development. As a .NET developer, .NET Framework makes it easy to perform these tasks.
Before you start, have to import System.IO.
[VB.Net]
Imports System.IO
[C#]
using System.IO;
1.Reading File
There are different ways that you can use them for reading file,
if you want to read a whole file as string, this ways could be fine for you:
[VB.Net]
Dim Result As String = File.ReadAllText("C:\CodingTips.txt")
[C#]
string Result = File.ReadAllText("C:\\CodingTips.txt");
if you need more properties and futures ,
same as searching specific text in the file, I suppose this ways is more efficient:
[VB.Net]
Private Sub Readfile() Dim strReader As StreamReader = File.OpenText("C:\CodingTips.txt") ' We will Search the stream until we reach the end or find the specific string. While Not strReader.EndOfStream Dim line As String = strReader.ReadLine() If line.Contains("Code") Then 'If we find the specific string, we will inform the user and finish the while loop. Console.WriteLine("Found Code:") Console.WriteLine(line) Exit While End If End While ' Here we have to clean the memory. strReader.Close() End Sub
[C#]
private void Readfile() { StreamReader strReader = File.OpenText("C:\\CodingTips.txt"); // We will Search the stream until we reach the end or find the specific string. while (!strReader.EndOfStream) { string line = strReader.ReadLine(); if (line.Contains("Code")) { //If we find the specific string, we will inform the user and finish the while loop. Console.WriteLine("Found Code:"); Console.WriteLine(line); break; // TODO: might not be correct. Was : Exit While } } // Here we have to clean the memory. strReader.Close(); }
In the next post I will teach you , How to write a file 🙂