Question

I have an ASCII-extended txt file and i need to convert it to a byte array. The problem is that the Null char and the space are decoded with the same 0x20 value. How I can discriminate between these cases? The file is created by a serial logger hardware that the saves the bytes exchanged on the serial port in a ASCII extended txt file. Here is the console app code:

class Program
{
    static void Main(string[] args)
    {
        Encoding enc = Encoding.GetEncoding(1252);
        byte[] byteArray;

        string filePath = "C:\\Log.txt";
        if (File.Exists(filePath))
        {
            StreamReader sr = new StreamReader(filePath, enc);
            string fileString = sr.ReadToEnd();
            if (fileString.Length > 0)
            {
                byteArray = enc.GetBytes(fileString);
                for (int i = 0; i < fileString.Length; i++)
                {
                    Console.WriteLine(fileString[i] + byteArray[i].ToString("X2"));
                }
            }
            else
            {
                Console.WriteLine("File is empty");
            }
        }
        else {
            Console.WriteLine("File " + filePath +" does not exit");            
        }
        Console.WriteLine("Press any key to stop...");
        Console.ReadKey();

    }
}
Was it helpful?

Solution

I have an ASCII-extended txt file and i need to convert it to a byte array.

Then don't go via text at all. If you just want to grab the bytes within a file, that's really easy:

byte[] data = File.ReadAllBytes(filePath);

Any time you find yourself decoding bytes to get to text, and then encoding that text with the same encoding to get at the bytes, you should be asking yourself whether you really need that text conversion in the first place.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top