[C#]產生順序GUID

[C#]產生順序GUID

上一篇透過SQL Server產生順序GUID,

那C#是否可產生如同 NEWSEQUENTIALID() function效果呢?

G了一下大多都只有直接使用 rpcrt4.dll,

windows mac address都是透過rpcrt4.dll來產生,

但只有單單使用rpcrt4.dll所產生GUID還是和NEWSEQUENTIALID() function有一些差異,

 

SQL Server執行結果如下


declare @myguid varchar(36),@ff varchar(max),@i int
set @i=1
while(@i<=20)
begin
exec usp_genguid @myguid output
print @myguid
set @i+=1;
end

 

image

頭2字元順序產生。

 

單單使用rpcrt4.dll結果如下


public class GuidTools
    {     
        [DllImport("rpcrt4.dll", SetLastError = true)]
        static extern int UuidCreateSequential(out Guid guid);
        public static Guid UuidCreateSequential()
        {
            const int RPC_S_OK = 0;
            Guid g;
            int hr = UuidCreateSequential(out g);
            if (hr != RPC_S_OK)
                throw new ApplicationException
                  ("UuidCreateSequential failed: " + hr);
            return g;
        }

        public static Guid ConvertToSqlServer(Guid guid)
        {
            byte[] guidBytes = guid.ToByteArray();
            Array.Reverse(guidBytes, 0, 4);
            Array.Reverse(guidBytes, 4, 2);
            Array.Reverse(guidBytes, 6, 2);
            return new Guid(guidBytes);
        }

    }

 


StringBuilder sb = new StringBuilder();
            for (int i = 0; i <= 20; i++)
            {
                sequentialGuid = GuidTools.UuidCreateSequential();
                sb.AppendLine(sequentialGuid.ToString());
                //sb.AppendLine(GuidTools.ConvertToSqlCompatible(sequentialGuid).ToString());             
            }
                MessageBox.Show(sb.ToString());

image

後2字元順序產生。

 

為符合SQL Server,透過Array.Reverse來調換相關字元位置


StringBuilder sb = new StringBuilder();
            for (int i = 0; i <= 20; i++)
            {
                sequentialGuid = GuidTools.UuidCreateSequential();
                //sb.AppendLine(sequentialGuid.ToString());                
                sb.AppendLine(GuidTools.ConvertToSqlServer(sequentialGuid).ToString());             
            }
                MessageBox.Show(sb.ToString());

結果

image

這樣就和NEWSEQUENTIALID() function規則相同。

 

參考

Generating NewSequentialID compatible Sequential Guids in C#

UuidCreateSequential