manemawanna
manemawanna

Reputation: 543

Converting Byte Array to delimited String of raw byte values

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.

Upvotes: 0

Views: 2534

Answers (5)

manemawanna
manemawanna

Reputation: 543

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

Upvotes: 0

Manitra Andriamitondra
Manitra Andriamitondra

Reputation: 1249

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);
    }

Upvotes: 0

Bill
Bill

Reputation: 2461

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.

Upvotes: 0

SLaks
SLaks

Reputation: 887857

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.

Upvotes: 3

Mongus Pong
Mongus Pong

Reputation: 11477

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 );

Upvotes: 0

Related Questions