开发者

Can't read a file with null bytes?

Hey guys I'm trying to read this file that has null bytes ( 00 hex ) sort of like padding. Every time I try to read the text it stops at the first null byte ( 00 hex ) does an开发者_Python百科ybody know how to get around this?


You will have to read it as binary data and then few instructions at this link to handle your byte data. Removing trailing nulls from byte array in C#


Use File.ReadAllBytes Method.


Here is an example, using FileReadAllBytes, of reading an otherwise "text" file that contains hex 00 nulls as well as other special characters.

Background: The old Borland Database Engine from Paradox and Delphi days has a config file, named either IDAPI.CFG or IDAPI32.CFG. The file is mostly normal text, but also contains the ASCII characters 0 (null) through 4. I needed to read this file to determine the current value of the "NET DIR" setting, and skip over the nulls.

The approach: 1) Read the file as a stream of bytes, in one big (or small) gulp into a byte array. The important statement is byte[filecontents] = File.ReadAllBytes(fileName).

2) Read and process each character in the byte array. For each character... * If null, ignore it * If other selected character, (ASCII 01 thru 04) either ignore it or transform to a different character representing its function, e.g., NewLine or equals sign. * If other (e.g. displayable) ASCII character, transform the byte back into a character form and append to an output stringbuilder. The line of code that does this is textOut.Append((char)fileByte)

        private string GetBDEConfigText(string fileName)
    {
        StringBuilder textOut = new StringBuilder();
        byte[] fileContents = File.ReadAllBytes(fileName);
        foreach (byte fileByte in fileContents)
        {
            switch (fileByte)
            {
                case 0:
                    {
                        // Leave unchanged, strip out binary character
                        break;
                    }
                case 1:
                    {
                        // Leave unchanged, strip out binary character
                        break;
                    }
                case 2:
                    {
                        break;
                    }
                case 3:
                    {
                        textOut.Append(Environment.NewLine);
                        break;
                    }
                case 4:
                    {
                        textOut.Append('=');
                        break;
                    }
                default:
                    {
                        textOut.Append((char)fileByte);
                        break;
                    }
            }
        }
        return textOut.ToString();
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜