File Encoding And Decoding In .Net Using Simple IO Operations

BackGround:
 
For providing security for for our files we need some encoding facility in application. Then we can send those encoded files over the network. Here we will see the encoding and decoding of files using System.IO namespace provided by .Net.
 
Let's start our work step-by-step
 
Step 1:
 

Create C# windows form application and design the form as bellow.

windows form in .net
 
Step 2:
 
Add using directive to System.IO namespace of .net framework and write this two methods.
 
         private
void DecodeFile(string srcfile, string destfile)
         {
             string src;
             StreamReader sr = new StreamReader(srcfile)
             src = sr.ReadToEnd();
             sr.Close();
             byte[] bt64 = System.Convert.FromBase64String(src);
             if (File.Exists(destfile))
             {
                 File.Delete(destfile);
             }
             FileStream sw = new FileStream(destfile, FileMode.Create);
             sw.Write(bt64, 0, bt64.Length);
             sw.Close();
         }
         private void EncodeFile(string srcfile, string destfile)
         { 
             string dest;
             FileStream sr = new FileStream(srcfile, FileMode.Open);
             byte[] srcbt = new byte[sr.Length];
             sr.Read(srcbt, 0, (int)sr.Length);
             sr.Close();
             dest = System.Convert.ToBase64String(srcbt);
             StreamWriter sw = new StreamWriter(destfile, false);
             sw.Write(dest);
             sw.Close();
         }
 

Decode and EncodeFile which will take sourcefilename and destination filenames as input. But here DecodeFile method source filename must be encoded file by EncodeFile.
 
Step 3:
 
Call this method in Encode and Decode button click event respectively. After encoding file you may see the file content will look like bellow screen shot.

Encode and Decode in .net
 
While actual data of the file is something different like bellow.

.net Encode and Decodein
 
Step 4:
 
Execute the application and do encoding and decoding of files from .net. It's pretty easy.
 
Conclusion:
 
Using normal System.IO operation we can encrypt file i.e. not readable format and again decrypt those file to original state.