Convert Binary file to Ascii and vice versa

Hi,
is there a simple way of converting a binary file to ascii file and vice versa
Thanks,
-srinivas yelamanchili


Answer this question

Convert Binary file to Ascii and vice versa

  • MShetty

    You cannot convert binary data directly to ASCII these days, ASCII can only represent character codes between 0 and 127. A common workaround is to use Convert.ToBase64String to convert binary data into a Base64 encoding string that only uses ASCII characters...


  • dariodario

    Hi,

    You can write strings to binary and read binary to string as follows:

    // ASCII Content
    string ContentOfTheFile = "This is a sample text prepared for ysrini!";
    long MoreContent = 5000;

    // We write the binary file
    using (FileStream TargetFile = new FileStream("C:\\Test.bin", FileMode.Create, FileAccess.Write))
    {

    BinaryWriter MyWriter = new BinaryWriter(TargetFile);
    MyWriter.Write(ContentOfTheFile);
    // as string
    MyWriter.Write(MoreContent); // as binary

    }

    // Read the binary into a string
    using (FileStream ReadFile = new FileStream("C:\\Test.bin", FileMode.Open, FileAccess.Read))
    {
    BinaryReader MyReader = new BinaryReader(ReadFile);
    string ReadContent = MyReader.ReadString();
    long ReadCharContent = MyReader.ReadInt64();

    Debug.WriteLine("Your string content: " + ReadContent + " and number " + ReadCharContent.ToString());

    }

    Hope this helps

    Cheers



  • Convert Binary file to Ascii and vice versa