Generate GUID from any string using C#
- by Haitham Khedre
Some times you need to generate GUID from a string which is not valid for GUID constructor . so what we will do is to get a valid input from string that the GUID constructor will accept it. It is recommended to be sure that the string that you will generate a GUID from it some how unique. The Idea is simple is to convert the string to 16 byte Array which the GUID constructor will accept it. The code will talk : using System;
using System.Text;
namespace StringToGUID
{
class Program
{
static void Main(string[] args)
{
int tokenLength = 32;
int guidByteSize = 16;
string token = "BSNAItOawkSl07t77RKnMjYwYyG4bCt0g8DVDBv5m0";
byte[] b = new UTF8Encoding().GetBytes(token.Substring(token.Length - tokenLength, tokenLength).ToCharArray(), 0, guidByteSize);
Guid g = new Guid(b);
Console.WriteLine(g.ToString());
token = "BSNePf57YwhzeE9QfOyepPfIPao4UD5UohG_fI-#eda7d";
b = new UTF8Encoding().GetBytes(token.Substring(token.Length - tokenLength, tokenLength).ToCharArray(), 0, guidByteSize);
g = new Guid(b);
Console.WriteLine(g.ToString());
Console.Read();
}
}
}
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
And The output:
37306c53-3774-5237-4b6e-4d6a59775979
66513945-794f-7065-5066-4950616f3455