Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to write byte array to file

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 815
    Comment on it

    In C#, many times we need to write a byte array to file. In this blog, we are going to illustrate how to write the byte array to file by using three methods.

     

    1. By using File.WriteAllBytes(string , byte[] ) Method

     

    This method is used to write the specified byte of an array to the file. If the file name specified in path previously exists then, it will overwrite its contents. But if the file name does not exist then, it will create a new file with the specified file name. After the write operation is completed, this method automatically closes that file.

     

    Syntax:

    public static void WriteAllBytes( string path ,byte[] bytes )

     

    It accepts two parameters:

     

    1. path:- It is the path of a file in which the specified byte array is written. Its return type is System.String.

    2. bytes:- It contains a byte array to write to the file. Its return type is System.Byte[].

     

    A sample C# code shows how to write data to a file

    using System;
    using System.IO;
    
    namespace ConsoleApplication1
    {
        class SampleProgram
         {
             public static void Main(string[] args)
              { 
                 string pathName = @"D:\SubFolder\f2.txt";
                 byte[] arrayBytes= { 100,101,102 };
                 File.WriteAllBytes(pathName, arrayBytes);
                 Console.ReadKey();
               }
           }
       }

     

    2. FileStream.WriteByte() Method

     

    This method is used to write a byte to the specified byte of an array to the file stream. This method will throw an exception if the stream is closed or not able to open in write mode.

     

    Syntax:-

    public override void WriteByte( byte value )

    It accepts parameter "value" which define a byte to write to the stream.

     

    Exceptions:

     

    This method throws the following exceptions:

     

    1. ObjectDisposedException ------------> It occurs if the file stream is closed.

    2. NotSupportedException ----------> It occurs if the file stream does not support write operation.

     

    A sample C# code shows how to write data to a file

     

    using System;
    using System.IO;
    
    namespace ConsoleApplication1
    {
        class SampleProgram
         {
             public static void Main(string[] args)
              {
                  const string fileName = @"D:\SubFolder\f3.txt";
                  byte[] arrayBytes= new byte[3];
                  arrayBytes[0] = 100;
                  arrayBytes[1] = 101;
                  arrayBytes[2] = 102;
                  using (FileStream fs = new FileStream(fileName, FileMode.Create))
                    {
                       for (int i = 0; i < arrayBytes.Length; i++)
                         {
                            fs.WriteByte(arrayBytes[i]);
                         }
                       fs.Seek(0, SeekOrigin.Begin);               
                    }
                  Console.ReadKey();
             }
         }
      }
    

     

     

    3. BinaryWriter.Write Method (String)

     

    This method writes a built-in data types as binary values in a specifically formatted stream by using BinaryWriter Class.

    Using this method, we secure our files because Binary information is not easily read by the human.

    This method is also good for the memory utilization.

     

    Syntax:-

    public virtual void Write( string variablename )

     

    It accepts one parameter "variablename" which defines the value to write.

     

    Exceptions:

     

    This method throws the following exceptions:

     

    1. IOException --------> It occurs if any I/O error.

    2. ArgumentNullException --------> It occurs if writing value is null.

    3. ObjectDisposedException -------> It occurs if the file stream is closed.

     

    A sample C# code shows how to write data to a file

    using System;
    using System.IO;
    
    namespace ConsoleApplication1
    {
        class SampleProgram
         {
              public static void Main(string[] args)
               {
                   BinaryWriter wr = null;
                   string FName = @"D:\SubFolder\f4.txt";
                    wr = new BinaryWriter(File.OpenWrite(FName));
                    byte[] arrayBytes = new byte[3];
                    arrayBytes[0] = 100;
                    arrayBytes[1] = 101;
                    arrayBytes[2] = 102;
                    wr.Write(fb);
                    wr.Flush();
                    wr.Close();
                    Console.ReadKey();
               }
          }
    }

     

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: