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 🙂
This design is incredible! You definitely know how to keep a reader entertained.
Between your wit and your videos, I was almost moved to start
my own blog (well, almost…HaHa!) Great job. I really loved what you had to say,
and more than that, how you presented it. Too cool!
How To Write File Through VB.Net & C#, now is published 🙂
Good day I am so grateful I found your blog page, I really found you
by accident, while I was researching on Askjeeve for
something else, Regardless I am here now and would just like to say kudos for a fantastic post
and a all round exciting blog (I also love the theme/design), I don’t have time to browse it all at
the moment but I have saved it and also included your RSS
feeds, so when I have time I will be back to read more, Please do keep up the awesome b.