Converting Byte Array to delimited String of raw byte values - c#

I'm in the process of creating an application which will monitor specific registry key values for changes and write those changes to a text file.
At present I can monitor the changes and know when specific values have changed and collect the data held in those values. The problem I'm having at the moment is the return type of the data is Byte and I wish to convert this to String initially for display so I know it returns the right value and then can be saved to a text file.
The reason I'm asking is that later on the next time the user logs onto a system those keys will be created or changed to match the previous values. (Were doing this as a way to save user preferences as were currently using mandatory profiles).
If anyone has any advice it would be appreciated.

It depends what the bytes are.
You need to figure out what encoding the bytes were generated from, then write something like this:
string str = Encoding.UTF8.GetString(bytes);
Depending on how the bytes were made, you may need to use Encoding.ASCII or Encoding.GetEncoding.

You first need to decide what encoding the bytes are in before converting to a string..
Then :
System.Text.Encoding enc = System.Text.Encoding.ASCII;
string myString = enc.GetString(myByteArray );

The System.Text.Encoding class has static methods to convert bytes into strings. In your case, you will want to use System.Text.Encoding.ASCII.GetString(bytes). Use other encodings (UTF8, UTF16) as appropriate.

Instead of using a specidief encoding, use the default one of your system :
public string ReadBytes(byte[] rawData)
{
//the encoding will prolly be the default of your system
return Encoding.Default.GetString(rawData);
}

Right I've now been able to resolve this by storing the registry value in a byte array, then adding each part of the array to a string, using the following code:
RegistryKey key = Registry.Users.OpenSubKey(e.RegistryValueChangeData.KeyPath);
Byte[] byteValue = (Byte[])key.GetValue(e.RegistryValueChangeData.ValueName);
string stringValue = "";
for (int i = 0; i < byteValue.Length; i++)
{
stringValue += string.Format("{0:X2} ", byteValue[i]);
}
Thanks for all the suggestions

Related

Converting Byte[] to string to remain the original byte format

I have large amount of data which consists of tables,font,bold,size,etc. Those data will be stored as byte[] in Database.
when i retrieve those data i need to convert byte[] into string,because i need to some find & replace from this string,after i convert this string into byte[],am losing the original data structure which means, i can't able to see any tables,font,bold etc. properly. So how can i find and replace in byte[] by converting string and also to keep remain the data in original format.
The short answer is don't. Figure out the format of the data and see what you can do to do the manipulation. If the data is actually text, just stored as byte[], your approach would work, provided you encode the string correctly (ie. if your DB expects UTF-8, use UTF-8 encoding, if it's windows-1251, use that).
If you have a structure where a part of it is a string, what you're doing can't really work well. First, you probably want to modify just the relevant parts of the field. On MS SQL, you have handy functions for that. But even then, you should know what's actually stored there, not just assume that a string replace will magically work.
Now, a hack could be to use an explicit encoding that doesn't break the non-string data. That would be some single-byte encoding that doesn't do anything fancy. This is OK as long as you use the same encoding while reading the text data - however, if you use any variant of unicode, you're out of luck; due to features like string normalization, you can't really guarantee that what comes in comes out the same way, per-byte. It's generally a bad practice anyway.
Don't forget that it's quite possible the string you are looking for is actually somewhere outside of the text fields - even by pure chance, it can happen, and certain practices make that even more likely.
Again: figure out the data format inside that data field - then you can decide how to do what you want.
Try this
string result = System.Text.Encoding.UTF8.GetString(byteArray)
To make Byte[] to String
byte[] byteArray = new byte[10]; // put your byte array here
public void byteToString()
{
stringTemp = "";
stringTemp = BitConverter.ToString(byteArray).Replace("-", "");
}
And your data still in byteArray.. :)
If the byte Array contains binary data and is no string, try to convert it to base64:
Convert.ToBase64String(yourByteArray);

Exif field ImageDescription adding data is not fully successful

Hope to seek some help.
I am trying to add some text to Exif field ImageDescription(270). I am partially successful.
Here is the code
pitem.Id = 270;
pitem.Type = 2;
byte[] utf16Bytes = Encoding.Unicode.GetBytes("Testing ImageDescription from command line.");
byte[] utf8Bytes = Encoding.Convert(Encoding.Unicode, Encoding.UTF8, utf16Bytes);
pitem.Value = utf8Bytes;//utf16Bytes
image.SetPropertyItem(pitem);
I then save image copy at new path, then I try to read back the property just added. THIS is where I am so failing..:-(
For some reason this field is not taking more then 6 characters, I have tried many things including change data to UTF-8 byte array, adding null-terminator (\0), even tried another field (305) with the same issue there as well, field will not take more then 6 characters.. I am not being able to see the full text being added to the field. Can some one guide..
Thanks
2 things:
(a) Look at PropertyItem.Type definition:
1: Specifies that Value is an array of bytes.
2: Specifies that Value is a null-terminated ASCII string. If you set the type data
member to ASCII type, you should set the Len property to the length of
the string including the null terminator. For example, the string
"Hello" would have a length of 6.
Looks like you are using it wrong - either it should be (1) - and then you should save array of bytes, or it should be (2) - but then you need to pass ASCII string to it.
Look at this question as well: Set image meta data before save
(b) Set ptype.Len property to the length of the string.
http://msdn.microsoft.com/en-us/library/system.drawing.imaging.propertyitem.type.aspx

Byte array to text for ScintillaNET

I'm writing a windows forms application in c#. The application allows the user to select source code-files from a listbox and displays them in colored code using ScintillaNET. The files are saved as byte arrays in a database. I've managed to make the conversion from a file on my hard drive to byte array and store it. The user should also be able to edit the code and then save it to the database without having to dowload the file to their local hard drive first, I don't know how to approach this.
Basically I want to save the text from the ScintillNET control and convert it to a byte array.
And the other way around, take a byte array and print out the text as it originally appeared in ScintillaNET.
You can use the "Encoding" class from System.Text.
System.Text.Encoding.Unicode.GetBytes("Example");
This will return a byte array with the bytes equivalent to the text "string" using the unicode encoding. There are other encoding available, but I suggest using unicode since it supports more characters (anything you find in windows charmap, for example). In my case is because I'm latin and certain letters aren't available in UTF and I have my doubts about ASCII.
Now to convert from the byte array to string use:
byte[] exampleByteArray = MemStream.ToArray();
System.Text.Encoding.Unicode.GetString(exampleByteArray);
This code will return the string saved previously as a byte array in a memory stream. You can load the byte array with other methods, in you your case you are gonna load it from the database and call System.Text.Encoding.Unicode.GetString().
I believe you are looking for the System.Text.Encoding namespace...
// a sample string...
string example = "A string example...";
// convert string to bytes
byte[] bytes = Encoding.UTF8.GetBytes(example);
// convert bytes to string
string str = System.Text.Encoding.UTF8.GetString(bytes);

How to convert between string and byte[] without losing integrity

I know how to convert from a string to byte[] in C#. In this particular case, I'm working with the string representation of an HMAC-SHA256 key. Let's say the string representation of this key I get from an OpenID OP is:
"81FNybKWfcM539vVGtJrXRmoVMxNmZHY3OgUro8+pZ8="
I convert it to byte[] like this:
byte[] myByteArr = Encoding.UTF8.GetBytes("81FNybKWfcM539vVGtJrXRmoVMxNmZHY3OgUro8+pZ8=");
The problem I have with that is that it seems to be losing the original data. If I take the byte array from the previous step and convert it back to a string, it's different from the original string.
string check = Convert.ToBase64String(myByteArr);
check ends up being:
"ODFGTnliS1dmY001Mzl2Vkd0SnJYUm1vVk14Tm1aSFkzT2dVcm84K3BaOD0="
which is obviously not the same as the original string representation I started with.
With crypto keys, always use Convert.FromBase64String and Convert.ToBase64String. That way you'll be doing it the standard way and will not lose bytes due to encoding problems. Base 64 string may not be space efficient but it is the preferred method for storage and transport of keys in many schemes.
Here is a quick verification:
byte[] myByteArr = Convert.FromBase64String("81FNybKWfcM539vVGtJrXRmoVMxNmZHY3OgUro8+pZ8=");
string check = Convert.ToBase64String(myByteArr);
Console.WriteLine(check);
// Writes: 81FNybKWfcM539vVGtJrXRmoVMxNmZHY3OgUro8+pZ8=
The first function (Encoding.UTF8.GetBytes) takes a string (of any kind) and returns a byte[] that represents that string in a particular encoding -- in your case, UTF8.
The second function (Convert.ToBase64String) takes a byte array (of any kind) and returns a string in base64 format so that you can store this binary data in any ASCII-compatible field using only printable characters.
These functions are not counterparts. It looks like the string you're getting is a base64-encoded string. If this is the case, use Convert.FromBase64String to get the byte[] that it represents, not Encoding.UTF8.GetBytes.
The bytes you get when using byte[] Encoding.GetBytes(string) and decoding a base64 string are not the same things. The former gives you the bytes that represent the string. You however want to decode a base64 string back to the bytes it represents. In that case you want to use Convert.FromBase64String().
string encoded = "81FNybKWfcM539vVGtJrXRmoVMxNmZHY3OgUro8+pZ8=";
byte[] decoded = Convert.FromBase64String(encoded); // this gives the bytes that the encoded string represents
The encoding classes have a GetString method, to convert it from a byte array back to a string.
If you used the UTF8 encoding to create the byte array, you should use the same coding to get it back again.
var original = "81FNybKWfcM539vVGtJrXRmoVMxNmZHY3OgUro8+pZ8=";
var byteArray = Encoding.UTF8.GetBytes(original);
var copy = Encoding.UTF8.GetString(byteArray);
bool match = (copy == original); // This returns true

Converting SQL Server varBinary data into string C#

I need help figuring out how to convert data that comes in from a SQL Server table column that is set as varBinary(max) into a string in order to display it in a label.
This is in C# and I'm using a DataReader.
I can pull the data in using:
var BinaryString = reader[1];
i know that this column holds text that was previously convert to binary.
It really depends on which encoding was used when you originally converted from string to binary:
byte[] binaryString = (byte[])reader[1];
// if the original encoding was ASCII
string x = Encoding.ASCII.GetString(binaryString);
// if the original encoding was UTF-8
string y = Encoding.UTF8.GetString(binaryString);
// if the original encoding was UTF-16
string z = Encoding.Unicode.GetString(binaryString);
// etc
The binary data must be encoded text - and you need to know which encoding was used in order to accurately convert it back to text. So for example, you might use:
byte[] binaryData = reader[1];
string text = Encoding.UTF8.GetString(binaryData);
or
byte[] binaryData = reader[1];
string text = Encoding.Unicode.GetString(binaryData);
or various other options... but you need to know the right encoding. Otherwise it's like trying to load a JPEG file into an image viewer which only reads PNG... but worse, because if you get the wrong encoding it may appear to work for some strings.
The next thing to work out is why it's being stored as binary in the first place... if it's meant to be text, why isn't it being stored that way.
You need to know what encoding was used to create the binary. Then you can use
System.Text.Encoding.UTF8.GetString(reader[1]);
And change UTF8 for whatever encoding was used.

Categories