Skip to content

Convert Byte[] to string

arul

Asked Sep 16, 2008, 2:57 AM EDT2 answers
Share
LinkedInX

Hi,
i want to get the PST file path from the registry using c# windows application.this is code.

RegistryKey rootKey = Registry.Users.OpenSubKey(@"S-1-5-21-1107897091-684665201-52263381-211903\Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles\Microsoft Outlook\0a0d020000000000c000000000000046");
            ASCIIEncoding enc = new  ASCIIEncoding();
            byte[] ans = (byte[])rootKey.GetValue("001f0324");
            MessageBox.Show(enc.GetString(ans).ToString());
        
            for (int x = 0; x < ans.Length; x++)
            {
                listBox1.Items.Add(String.Format("{0:x2}", ans[x]));
            }
here the output(enc.GetString(ans)) string return only "C".the actual output in the registry is "C:\Documents and Settings.....pst" 
but i could not get the full value.
how can i do it? can you please help me out ?

Thanks and Regards

Arul

2 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • Mahesh Chand
    0
    Look at the Convert class. Here is an article.
    The Convert class takes care of most of the data type conversions in . ... public static string ToString(byte);, Converts a Byte to a String. ...
    0
  • 0
    The data you're reading from the registry is actually a unicode "C" string. You can use System.Text.Encoding.Unicode.GetString() to convert the byte array to a string. However, this leaves a unicode "nul" at the end of the string. One alternative is use the marshal class to copy the bytes into an unmanaged buffer and then use the marshal class to convert the null terminated unicode string, as follows (assumes that k contains your open registry key object):

    using System.Runtime.InteropServices;

     ...
                byte[] barr = (byte[])k.GetValue("001F0324");

                int numbytes = barr.Length;
                IntPtr punmanaged = Marshal.AllocHGlobal(numbytes);
                Marshal.Copy(barr, 0, punmanaged, numbytes);
                string keyVal = Marshal.PtrToStringUni(punmanaged);
                Marshal.FreeHGlobal(punmanaged);

    There are lots of ways to convert between managed strings and arrays of bytes - which is best for your situation is your choice.
    0