简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM