The System.Guid is used whenever we need to generate a unique key, but it is very long. That’s in many cases not an issue, but in a web scenario where it is part of the URL we need to use its string representation which is 36 characters long. It clutters up the URL and is just basically ugly.
It is not possible to shorten it without loosing some of the uniqueness of the GUID, but we can come a long way if we can accept a 16 character string instead.
We can change the standard GUID string representation:
21726045-e8f7-4b09-abd8-4bcc926e9e28
Into a shorter string:
3c4ebc5f5f2c4edc
The following method creates the shorter string and it is actually very unique. An iteration of 10 million didn’t create a duplicate. It uses the uniqueness of a GUID to create the string.
private string GenerateId()
{
long i = 1;
foreach (byte b in Guid.NewGuid().ToByteArray())
{
i *= ((int)b + 1);
}
return string.Format("{0:x}", i - DateTime.Now.Ticks);
}
If you instead want numbers instead of a string, you can do that to but then you need to go up to 19 characters. The following method converts a GUID to an Int64.
private long GenerateId()
{
byte[] buffer = Guid.NewGuid().ToByteArray();
return BitConverter.ToInt64(buffer, 0);
}
The standard GUID is still the best way to ensure the uniqueness even though it isn’t 100% unique.
A couple of days ago, I had to store some very big strings in an XML file. To keep the file size down I wanted to compress the strings using a GZipStream and then decompress them later when needed.
I modified the methods from Papenoo pa so they handled strings in stead of byte arrays.
using System.IO.Compression;
using System.Text;
using System.IO;
publicstaticstring Compress(string text)
{
byte[] buffer = Encoding.UTF8.GetBytes(text);
MemoryStream ms =new MemoryStream();
using (GZipStream zip =new GZipStream(ms, CompressionMode.Compress, true))
{
zip.Write(buffer, 0, buffer.Length);
}
ms.Position = 0;
MemoryStream outStream =new MemoryStream();
byte[] compressed =newbyte[ms.Length];
ms.Read(compressed, 0, compressed.Length);
byte[] gzBuffer =newbyte[compressed.Length + 4];
System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);
System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);
return Convert.ToBase64String (gzBuffer);
}
publicstaticstring Decompress(string compressedText)
{
byte[] gzBuffer = Convert.FromBase64String(compressedText);
using (MemoryStream ms =new MemoryStream())
{
int msgLength = BitConverter.ToInt32(gzBuffer, 0);
ms.Write(gzBuffer, 4, gzBuffer.Length - 4);
byte[] buffer =newbyte[msgLength];
ms.Position = 0;
using (GZipStream zip =new GZipStream(ms, CompressionMode.Decompress))
{
zip.Read(buffer, 0, buffer.Length);
}
return Encoding.UTF8.GetString(buffer);
}
}
The strings need to be longer than 3-400 characters; otherwise the compression rate is not good enough.