views:

104

answers:

5

Hello, 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.

A: 

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 );
Mongus Pong
+3  A: 

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.

SLaks
Exactly what OP is looking for. :D +1
Sergio Tapia
A: 

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.

Bill
A: 

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);
    }
Manitra Andriamitondra
This will use the system's current ANSI codepage. There is no guarantee that the data was encoded in it. http://msdn.microsoft.com/en-us/library/system.text.encoding.default.aspx
SLaks
A: 

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

manemawanna