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 anybody know how to get around this?
-
1Do you try to load this file as a text-file? If your file contains 0x0s, you have to read it in binary mode. – HCL May 05 '11 at 19:15
-
1Can you post your code to read the file? It sounds like it is being interpreted as a string ( where 0x00 signifies the end of the string ). – IanNorton May 05 '11 at 19:16
-
@IanNorton Yes this is what I have been doing. If i read it in binary how can i convert it to a string with out it ending like that? – user556396 May 05 '11 at 19:17
-
the 0 byte is internal the end of a string. You will have to find a different method of reading. You can read text file if you know the length. – Roger Far May 05 '11 at 19:18
3 Answers
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#
-
Thanks, I just tested it and it seemed to work after removing all the nulls. – user556396 May 05 '11 at 19:26

- 4,501
- 3
- 40
- 45
-
Now if i do this how could I use something like split on it seeing as it is not a string? – user556396 May 05 '11 at 19:19
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();
}

- 640
- 7
- 19