Create, Read and Write Files in .Net

In this article I will explain about how to create a file, how to read file and last how to write to file.

In .Net, if we want to work on Files we have to import namespace system.IO.

Create File:

To create file in .Net we have to use code like System.IO.File.Create(fullfilename)

Eg:
System.IO.File.Create(“C:/test.txt”)

The above code will create the note file in C drive with the name as test.txt.

Read File:

To Read file we have to use StreamReader.

Eg:
Dim fs As New FileStream(“C:/test.txt”, FileMode.Open, FileAccess.Read)
Dim reader As New StreamReader(fs)
Dim file_content As String = ""
reader.BaseStream.Seek(0, SeekOrigin.Begin)
While reader.Peek > -1
file_content = file_content + reader.ReadLine
End While


Here file_content will give the content of test.txt file.

Write File:

To write file we have to use streamreaders in .Net

Eg:
Dim sw As System.IO.StreamWriter
sw = New System.IO.StreamWriter(“C:/test.txt”, True)
SyncLock sw
sw.WriteLine(“Hi, I am from codedefiner”)
End SyncLock


The above code will write the given message in the test.txt file.

Below I am explaning File Create,Read and Write methods with an Example.



    Imports System.IO
    Public Class Form1

    Sub writeToFile(ByVal filename As String, ByVal msg As String)
        Dim sw As System.IO.StreamWriter
        Try
            Dim dir As String, fullfilename As String
            dir = "C:/"
            fullfilename = String.Concat(dir, filename)
            If System.IO.File.Exists(fullfilename) Then
                If FileLen(fullfilename) >= 5000000 Then Kill(fullfilename)
            Else
                System.IO.File.Create(fullfilename)
            End If

            sw = New System.IO.StreamWriter(fullfilename, True)
            SyncLock sw
                sw.WriteLine(msg)
            End SyncLock
            MessageBox.Show("File created and Message written to that File")
            txt_fileName.Text = ""
            txt_data.Text = ""
        Catch e As System.IO.IOException
            MessageBox.Show(e.Message)
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            If Not sw Is Nothing Then sw.Close()
        End Try

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) 
                        Handles Button1.Click
        txt_fileName.Text = txt_fileName.Text.Trim
        txt_data.Text = txt_data.Text.Trim

        If txt_fileName.Text = "" Then
            MessageBox.Show("Please Enter File Name")
            txt_fileName.Focus()
            Exit Sub
        End If
        If txt_fileName.Text.Contains(".") = False Then
            MessageBox.Show("Please enter file name with extension")
            txt_fileName.Focus()
            Exit Sub
        End If

        If txt_data.Text = "" Then
            MessageBox.Show("Please enter your Message")
            txt_data.Focus()
            Exit Sub
        End If

        writeToFile(txt_fileName.Text, txt_data.Text)
    End Sub

    Sub readFile(ByVal filepath As String)
        Try
            Dim fs As New FileStream(filepath, FileMode.Open, FileAccess.Read)
            Dim reader As New StreamReader(fs)
            Dim file_content As String = ""

            reader.BaseStream.Seek(0, SeekOrigin.Begin)
            While reader.Peek > -1
                file_content = file_content + reader.ReadLine
            End While
            reader.Close()
            If String.IsNullOrEmpty(file_content) Then
                file_content = "NO DATA IN " & filepath & " file"
            End If

            txt_FileData.Text = file_content

        Catch ex As Exception

        End Try

    End Sub
   
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) 
                Handles Button2.Click
        txt_readFile.Text = txt_readFile.Text.Trim
        If txt_readFile.Text = "" Then
            MessageBox.Show("Please full path of file to Read")
            txt_readFile.Focus()
            Exit Sub
        End If
        If System.IO.File.Exists(txt_readFile.Text) = False Then
            MessageBox.Show("Please enter correcty path of file to Read")
            txt_readFile.Focus()
            Exit Sub
        End If
        readFile(txt_readFile.Text)
    End Sub     
End Class


As shown above we have to methods. One is for create & write the contents to the file another is to read the contents.

To create the file you have to give file name. By default I am creating file in C directory, if you want you can change Directory. I am writing the contents to this file by using StreamWriter class.

To read the file you have to give full path of the file. The content of the given file will be displayed in textbox by using StreamReader class.


Download source code here

Recent Articles

CLR integartion in SQL Server
Create, Read and Write Files in .Net
Message Queue in .Net
Deploy Asp.Net Web Site
Queues in Vb.Net
If you have any queries or doubts post at Forum
Share on Facebook
Responses(post your response or comments below)
Name *

Email * (won't be published)

Response *