trimming string converted from byte[]

R

Rico

In the following piece of code:
*******************************************************
byte[] buffer = new byte[20];
string next_node=null, ret=null;
ASCIIEncoding encoding = new ASCIIEncoding();
BufferedStream sr = new BufferedStream (new FileStream (nodeptr, FileMode.Open ));

sr.Seek(6, SeekOrigin.Begin );
sr.Read (buffer, 0, 17);
next_node = encoding.GetString(buffer);

Console.WriteLine(next_node.Trim() + "__");
*******************************************************

I read 17 bytes from a text file as from the 7th byte onwards.
Why is it that the final WriteLine statement shows what appears to be
characters with ASCII code 0 in next_node before the "__" ?

A work-around is to set the size of buffer to exactly the number of bytes
I happen to know I need to read. What when I don't and overallocate space
in buffer, or when Read() says fewer bytes than requested were read and I
only want to convert those to a string?

Rico.
 
J

Jon Skeet [C# MVP]

Rico said:
In the following piece of code:
*******************************************************
byte[] buffer = new byte[20];
string next_node=null, ret=null;
ASCIIEncoding encoding = new ASCIIEncoding();

This line is unnecessary - you can just use Encoding.ASCII to avoid
creating a new encoding each time.
BufferedStream sr = new BufferedStream (new FileStream (nodeptr, FileMode.Open ));

sr.Seek(6, SeekOrigin.Begin );
sr.Read (buffer, 0, 17);
next_node = encoding.GetString(buffer);

Console.WriteLine(next_node.Trim() + "__");
*******************************************************

I read 17 bytes from a text file as from the 7th byte onwards.
Why is it that the final WriteLine statement shows what appears to be
characters with ASCII code 0 in next_node before the "__" ?

Because you've presented it with a buffer of 20 bytes and asked it to
convert the whole of it to a string - it's done exactly what you asked
it to.
A work-around is to set the size of buffer to exactly the number of bytes
I happen to know I need to read. What when I don't and overallocate space
in buffer, or when Read() says fewer bytes than requested were read and I
only want to convert those to a string?

You should use the return value of Read to know how much you've
actually read, and then use
Encoding.ASCII.GetString(buffer, 0, bytesRead);
 
R

Rico

You should use the return value of Read to know how much you've
actually read, and then use
Encoding.ASCII.GetString(buffer, 0, bytesRead);

I know this group is quite busy but it still seems there's space and
bandwidth for a 'Thank You Jon'.

Rico.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top