2012-01-12 55 views
4

有没有可能或有任何重载获得少于32个字符的GUID? 目前我使用这个说法,但它给我的错误限制GUID中的字符数

string guid = new Guid("{dddd-dddd-dddd-dddd}").ToString(); 

我想20个字符

+1

如果它有较少的字符,它不会是一个GUID。这将是一些其他不那么随机的价值​​。 – 2012-01-12 14:42:55

+0

看看这个答案,把它缩小到20个字符使用Ascii85编码:http://stackoverflow.com/a/3247983/945456 – 2013-01-04 16:00:23

+0

你想要一个GUID或者你想要一个20个字符的值?他们不一样。 – 2013-02-21 04:50:31

回答

3

一键可以使用ShortGuid。 Here is an example的实现。

在网址或其他对最终用户可见的地方使用ShortGuids是很好的。

下面的代码:

Guid guid = Guid.NewGuid(); 
ShortGuid sguid1 = guid; // implicitly cast the guid as a shortguid 
Console.WriteLine(sguid1); 
Console.WriteLine(sguid1.Guid); 

会给你这样的输出:

FEx1sZbSD0ugmgMAF_RGHw 
b1754c14-d296-4b0f-a09a-030017f4461f 

这是一个编码和解码方法的代码:

public static string Encode(Guid guid) 
{ 
    string encoded = Convert.ToBase64String(guid.ToByteArray()); 
    encoded = encoded 
    .Replace("/", "_") 
    .Replace("+", "-"); 
    return encoded.Substring(0, 22); 
} 

public static Guid Decode(string value) 
{ 
    value = value 
    .Replace("_", "/") 
    .Replace("-", "+"); 
    byte[] buffer = Convert.FromBase64String(value + "=="); 
    return new Guid(buffer); 
} 
+0

这是22个字符。问题表明他想要20个字符。您需要从BASE64升级到ASCII85以将这2个刮掉。见大卫的回答。 – Travis 2013-12-20 19:47:49