c#-4.0 - 限制 GUID 中的字符数

标签 c#-4.0 guid

是否有可能获得少于 32 个字符的 GUID?
目前我正在使用这个语句,但它给了我错误

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

我想要一个 20 个字符的键

最佳答案

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

在 URL 或最终用户可见的其他地方使用 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);
}

关于c#-4.0 - 限制 GUID 中的字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8836597/

相关文章:

c# - 错误 - 与当前连接关联的事务已完成但尚未处理

c#-4.0 - List<T> 的意外内存使用

c# - WCF 数据服务中的自定义路由

google-maps - 如何在 Windows Phone 8 应用程序中添加谷歌地图

sql-server - 如何使用 Delphi 以 SQL Server 方式对 GUID 进行排序

linq - 在LINQ to Entities中使用自定义方法/扩展方法的变通办法

c# - Guid.NewGuid().ToByteArray() 到字符串(数字)行是否仍然唯一

com - 何时更改类型库上的 GUID

c# - 比较基于散列的 GUID 与“Guid.NewGuid()”时是否有更大的碰撞机会?

c++ - 返回设备 GUID 和 Bios ID、C++、Linux