Skip to content

How to read a binary file, convert it into proper text format ?

prasad

Asked Feb 8, 2006, 8:08 PM EST2 answers
Share
LinkedInX
Hi frndz, I want to read a binary file with .DAT extension and convert the data into valid ASCII format. Can someone plz help me on this ?!! thanx - Prasadd

2 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    You must implement a deserialization process. If you know that the serialized object (binary) is or can be transformed into an string (ASCII code), only apply a cast to the deserialized object and gotcha!. the following code deserialize an object. The folowing code ONLY transform the binary object from an array of bytes (bytes[]).-

    /// <summary>
    /// Deserialize an object from an array of bytes.
    /// </summary>
    /// <param name="SerializedImage">The array of bytes with the object to deserialize</param>
    /// <returns>The object deserialized</returns>
    public static object BinaryTo(byte[] SerializedImage)
    {
        IFormatter formatter;
        MemoryStream memStream = null;
        Object objectFromBinary = null;
        //Cursor saveCursor = Cursor.Current;
        //try
        //{
            //Cursor.Current = Cursors.WaitCursor;
            try
            {
                memStream = new MemoryStream(SerializedImage);
                formatter = new BinaryFormatter();
                objectFromBinary = formatter.Deserialize(memStream);
            }
            catch (Exception exception)
            {
                mp_lasterror = exception.Message;
            }
            finally
            {
                if (memStream != null) memStream.Close();
            }
        //}
        //finally
        //{
        //    Cursor.Current = saveCursor;
        //}
        return objectFromBinary;
    }


    Regards
    CFQüeb
    0
  • 0
    Here is the code to deserialize the object reading the file:

    BinaryFormatter bf = new BinaryFormatter();
    bool IsFromArchive = true;
    string temporalfilename = "yourfile.dat";
    string m_data ="";
    string mp_lasterror = "";

    if (IsFromArchive)
    {
            if (File.Exists(Application.StartupPath + @"\Temp\" + temporalfilename))
            {
                FileStream fstream = new FileStream(Application.StartupPath + @"\Temp\" + temporalfilename,
                    FileMode.Open, FileAccess.Read);
                try
                {
                    m_data = (string) bf.Deserialize(fstream);
                }
                catch (Exception ex)
                {
                    mp_lasterror = ex.Message;
                }
                finally
                {
                    //todo
                }
                fstream.Close();
            }
            else
                MessageBox.Show("The file" + temporalfilename + " was not found in the path!");

    }

    Regards

    0