Oct
03
2006
Bytearray to string and string to bytearray
Posted by admin under
.NET
Right now I am in the middle of converting an ancient DOS system for a client - and it involves moving existing data (stored inside a fixed length binary file) into SQL Server - and there are no docs whatsovever when it comes to record layout.
Anyway - using a Hex Editor I managed to find out each record in the file was 763 bytes - so I whipped up this little loop:
FileStream oStream = File.OpenRead("f:\\aa2.txt");
byte[]bLine = new byte[768];
while (oStream.Read(bLine, 0, 763) == 763)
{
}
oStream.Close();
Fine - but now what. I need to look at the record trying to find patterns of how the fields are structured within it. Using a bytearray for that is no good - I wanted to put it into a string. And found myself looking in docs again - it's simply such a thing you never seems to remember.
So here it is:
Converting a byte array to a string
byte[]bLine = new byte[...];
//Fill with data
bLine = ...
//
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
string str = enc.GetString(bLine);
Converting a string to a bytearray
string sStr = "whatever";
System.Text.ASCIIEncoding enc=new System.Text.ASCIIEncoding();
byte []bArray = enc.GetBytes(sStr);