Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert byte[] or object to GUID

I assigned some value to object data type like,

object objData =dc.GetDirectoryEntry().Properties["objectGUID"].Value;

this object retun the value like {byte[16]} [0]: 145 [1]: 104 [2]: 117 [3]: 139 [4]: 124 [5]: 15 [6]: 255 [7]: 68 [8]: 142 [9]: 159 [10]: 208 [11]: 102 [12]: 148 [13]: 157 [14]: 179 [15]: 75

Then i casting this object to byte[], like

byte[] binaryData = objData as byte[];

It will also return like, {byte[16]} [0]: 145 [1]: 104 [2]: 117 [3]: 139 [4]: 124 [5]: 15 [6]: 255 [7]: 68 [8]: 142 [9]: 159 [10]: 208 [11]: 102 [12]: 148 [13]: 157 [14]: 179 [15]: 75

Then i convert the hex values from byte[] like,

string strHex = BitConverter.ToString(binaryData);

It will be return like **91-68-75-8B-7C-0F-FF-44-8E-9F-D0-66-94-9D-B3-4B**.. But i need the output like GUID format, How can i achieve this?

like image 997
Manikandan Sethuraju Avatar asked Jun 02 '12 12:06

Manikandan Sethuraju


3 Answers

How about using the Guid constructor which takes a byte array?

Guid guid = new Guid(binaryData); 

(You can then use Guid.ToString() to get it in text form if you need to.)

like image 173
Jon Skeet Avatar answered Sep 20 '22 11:09

Jon Skeet


byte[] binaryData = objData as byte[]; string strHex = BitConverter.ToString(binaryData); Guid id = new Guid(strHex.Replace("-", "")) 
like image 43
André Voltolini Avatar answered Sep 19 '22 11:09

André Voltolini


The long form would be (enter link description here):

public static string ConvertGuidToOctectString(string objectGuid)
{
    System.Guid guid = new Guid(objectGuid);
    byte[] byteGuid = guid.ToByteArray();
    string queryGuid = "";
    foreach (byte b in byteGuid)
    {
        queryGuid += @"\" + b.ToString("x2");
    }
    return queryGuid;
}
like image 44
Michael Flyger Avatar answered Sep 19 '22 11:09

Michael Flyger