How To Write File Through VB.Net & C#

ms_visual_studio

As I have promised ,today I am going to show you how to create a file, you can write (create) file in different ways same as reading file.

Before you start, have to import System.IO.

[VB.Net]

Imports System.IO

[C#]

using System.IO;

Writing File

Let met to start with the easiest way,

1.WriteAllText

With this function you can create and write file at the same time!

[VB.Net]

File.WriteAllText("c:\CodingTips.txt", "coding is easy !")

[C#]

File.WriteAllText("c:\\CodingTips.txt", "coding is easy !")

2.StreamWriter:

This Pattern is much like reading file.

[VB.Net]

Dim writer As StreamWriter =File.CreateText("c:\CodingTips.txt") 
writer.WriteLine("coding is easy") 
writer.Close()

[C#]

StreamWriter writer = File.CreateText("c:\\CodingTips.txt");
writer.WriteLine("coding is easy");
writer.Close();

3.MemoryStream:

Sometimes you will need to create a stream (the string that you want to write to the file) before you really need to store it somewhere (like in a file). for example you have 5 functions in your code, and each function has a specific result and you want to store the results of these functions in one file, you cannot use the methods that I explained above, in this case, first you need to prepare the stream and then write it to the file, for this purpose MemoryStream would be a good choice,

[VB.Net]

Dim memoryStrm As New MemoryStream()
Dim writer As New StreamWriter(memoryStrm) 

'This part can to be repeated anywhere in your code 
that you want to you want to append text to the memoryStream.
writer.WriteLine("Function1") 
writer.WriteLine("Result1")

[C#]

MemoryStream memoryStrm= new MemoryStream();
StreamWriter writer = new StreamWriter(memoryStrm);

//This part can to be repeated anywhere in your code 
that you want to you want to append text to the memoryStream.
writer.WriteLine("Function1");
writer.WriteLine("Result1");

After you prepared your MemoryStream you can write it to the file:

[VB.Net]

' Here you must ask the writer to push the data into the 
' underlying stream 
writer.Flush() 
' the create a file stream 
Dim MyFile As FileStream = File.Create("c:\CodingTips.txt") 
' now Write the MemoryStream to the file
memoryStrm .WriteTo(theFile) 
' the you have to Clean up the objects 
writer.Close() 
theFile.Close() 
memoryStrm .Close()

[C#]

// Here you must ask the writer to push the data into the 
// underlying stream 

{
    writer.Flush();
    // the create a file stream 
    FileStream MyFile = File.Create("c:\\CodingTips.txt");
    // now Write the MemoryStream to the file
    memoryStrm.WriteTo(theFile);
    // the you have to Clean up the objects 
    writer.Close();
    theFile.Close();
    memoryStrm.Close();
}

How Read a Files Through VB.Net & C#

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 🙂