0

I'm trying to read a plain text file (.txt) on Windows using C# into a byte array with base16 encoding. This is what I've got:

FileStream fs = null;
try
{
    fs = File.OpenRead(filePath);
    byte[] fileInBytes = new byte[fs.Length];
    fs.Read(fileInBytes, 0, Convert.ToInt32(fs.Length));
    return fileInBytes;
}
finally
{
    if (fs != null)
    {
        fs.Close();
        fs.Dispose();
    }
}

When I read a txt file with this content: 0123456789ABCDEF I get a 128 bits (or 16 bytes) array but what I wanted is a 64 bits (or 8 bytes) array. How can I do this?

1 Answer 1

2

You can read two bytes as a string and parse it using a hex number specification. Example:

var str = "0123456789ABCDEF";
var ms = new MemoryStream(Encoding.ASCII.GetBytes(str));
var br = new BinaryReader(ms);
var by = new List<byte>();
while (ms.Position < ms.Length) {
    by.Add(byte.Parse(Encoding.ASCII.GetString(br.ReadBytes(2)), NumberStyles.HexNumber));
}
return by;

Or in your case something along these lines:

        FileStream fs = null;
        try {
            fs = File.OpenRead(filePath);
            using (var br = new BinaryReader(fs)) {
                var by = new List<byte>();
                while (fs.Position < fs.Length) {
                    by.Add(byte.Parse(Encoding.ASCII.GetString(br.ReadBytes(2)), NumberStyles.HexNumber));
                }
                var x = by.ToArray();
            }
        } finally {
            if (fs != null) {
                fs.Close();
                fs.Dispose();
            }
        }
Sign up to request clarification or add additional context in comments.

2 Comments

where does NumberStyles come from? I get a message "doesn't exist in current context"
For future reference, press Control+Space and you will see using System.Globalization. That's where it comes from. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.