Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
ASP.NET
VB.Net
C-Sharp
SQL Server
 

How to Read bytes from and Write bytes in files using “FILE CLASS” using system.io in c# (.net 2.0).

Author: Zunnair
Download Source Code : 843_io.zip

In this simple article you will learn how to read bytes from a file and write bytes in a file using FILE class in C# .net 2.0

 In my previous article I discussed that how can you create, open and close a file using “FILE CLASS” (SYSTEM.IO).

We can directly read bytes from or write bytes in file by using the file class functions.

READ BYTES FROM FILE:

First of all create a file as I told in my previous article and write some data in it. File class provides us static function to read bytes from a file so we do not need to create an object of “File Class”. To read from a file we have ReadAllBytes() function of FILE CLASS.

When we want to read from a file first of all we have to open it but ReadAllBytes() function provide us a facility that It opens file by it self so we do not need to open it, we can directly call this function.

ReadAllBytes() function takes file path as a parameter and returns bytes (read from the file) as a byte array.

Convert these bytes in char array than convert it into string with the help of loop.

To demonstrate make a window application. Drag two text boxes and one button on the form. Write file path (like c:\\abc.txt) in the first textbox and press button. Text read from the file will come in second text box.

Now write the following code on button click event:

C#

rivate void btnread_Click(object sender, EventArgs e)

        {

            str = txtPath.Text;

            if (str != null)

            {

                if (File.Exists(str) == true)

                {

                    byte[] b = File.ReadAllBytes(str);

                    string str3=string.Empty;

                    char[] ab = new char[b.Length];

                    for (int j = 0; j < b.Length; j++)

                    {                      

                        ab[j]=Convert.ToChar(b[j]);

                        str3 = "" + Convert.ToString(ab[j]);

                    }

                        txtread.Text =str3;

                }               

                else

                    MessageBox.Show("INVALID PATH NO FILE");

 

            }

            else

                MessageBox.Show("Please wite Path");                       

        }

VB

Private Sub btnread_Click(ByVal sender As Object, ByVal e As EventArgs)

        str = txtPath.Text

        If str IsNot Nothing Then

            If File.Exists(str) = True Then

                Dim b As Byte() = File.ReadAllBytes(str)

                Dim str3 As String = String.Empty

                Dim ab As Char() = New Char(b.Length - 1) {}

                For j As Integer = 0 To b.Length - 1

                    ab(j) = Convert.ToChar(b(j))

                    str3 = "" & Convert.ToString(ab(j))

                Next

                txtread.Text = str3

            Else

                MessageBox.Show("INVALID PATH NO FILE")

            End If

 

        Else

            MessageBox.Show("Please wite Path")

        End If

 End Sub

As I told that ReadAllBytes() opens file by it self but I would like to tell that it also close file by it self so we do not have to close it by our self.

WRITE BYTES IN FILE:

Again File class provides us static function to write bytes in a file so we do not need to create an object of “File Class”. To write in a file we have WriteAllBytes() function of FILE CLASS.

To read from a file there should be a file and text in a file. But WriteAllBytes()function provides us a facility. It creates a file if file does not exist at the given path. But if file exists than it is overwritten.

When we want to write in a file first of all we have to open it but WriteAllBytes()function provide us a facility that It opens file by it self so we do not need to open it, we can directly call this function.

WriteAllBytes() function takes file path and array of bytes (which should be written in file) as a parameter. it returns nothing.

To demonstrate make a window application. Drag two text boxes and one button on the form. Write file path (like c:\\abc.txt) in the first textbox and write text in the second textbox than press button to write in file.

Now write the following code on button click event:

C#

private void btnwrite_Click(object sender, EventArgs e)

        {            

            str = txtPath.Text;

            if (str != null)

            {

               string str2 = txtwrite.Text;

               char[] abc = str2.ToCharArray();

               int size=0;

               size = abc.Length;

               byte[] byt = new byte[size];

               for (int i = 0; i < size; i++)

               {

                   byt[i] = Convert.ToByte(abc[i]);

                        

               }

               File.WriteAllBytes(str, byt);   

                               

                if (File.Exists(str) == true)

                {

                    MessageBox.Show("BYTE WRITTEN");

                }

                else

                    MessageBox.Show("INVALID PATH NO FILE");

 

            }

            else

                MessageBox.Show("Please wite Path");            

        }

VB

Private Sub btnwrite_Click(ByVal sender As Object, ByVal e As EventArgs)

        str = txtPath.Text

        If str IsNot Nothing Then

            Dim str2 As String = txtwrite.Text

            Dim abc As Char() = str2.ToCharArray()

            Dim size As Integer = 0

            size = abc.Length

            Dim byt As Byte() = New Byte(size - 1) {}

            For i As Integer = 0 To size - 1

                byt(i) = Convert.ToByte(abc(i))

 

            Next

            File.WriteAllBytes(str, byt)

 

            If File.Exists(str) = True Then

                MessageBox.Show("BYTE WRITTEN")

            Else

                MessageBox.Show("INVALID PATH NO FILE")

            End If

 

        Else

            MessageBox.Show("Please wite Path")

        End If

    End Sub

To write bytes in file first convert string in char array than convert it in bytes array and than pass as a parameter.

As I WriteAllBytes() opens file by it self but I would like to tell that it also close file by it self so we do not have to close it by our self.

Now write the following code on FORM LOAD event:

C#

private void Form1_Load(object sender, EventArgs e)

        {

 

            this.Text = "Devasp.net FILE HANDLING Application";

        }

VB

Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)

 

        Me.Text = "Devasp.net FILE HANDLING Application"

 End Sub

 

This simple article tells you how to read bytes from a file and write bytes.

   
Add Article Comment:
Name :
Email Address :
   
Comments :
 
   
<< How to GET and SET properties of any file using system.io namespace in c# (.net 2.0).

Disclaimer - Privacy
© 2002-2017 DevASP.net