我創建了一個簡單的程序。將二進制轉換爲字符串不起作用
我創建了一個字符串,並通過以下方法對其進行壓縮,並將其存儲在sql server 2008(binary(1000)
字段類型)中的二進制數據字段類型中。
當我讀取二進制數據和結果字符串是真正的像原始字符串數據具有相同的長度和數據,但當我想解壓縮它給了我一個錯誤。
我用這種方法來獲得字節:
System.Text.ASCIIEncoding.ASCII.GetBytes(mystring)
而且這種方法來獲得字符串:
System.Text.ASCIIEncoding.ASCII.GetString(binarydata)
在VS2012編輯硬編碼,結果字符串工作正常,但是當我讀它從SQL它給我這個錯誤的第一行解壓縮方法:
The input is not a valid Base-64 string as it contains a
non-base 64 character, more than two padding characters,
or a non-white space character among the padding characters.
我的代碼有什麼問題?這兩個字符串是相同的,但
string test1=Decompress("mystring");
...這種方法工作得很好,但是這給了我錯誤,無法解壓返回的字符串
string temp=System.Text.ASCIIEncoding.ASCII.GetString(get data from sql) ;
string test2=Decompress(temp);
的比較這些字符串不顯示任何尊重
int result = string.Compare(test1, test2); // result=0
我的壓縮方法:
public static string Compress(string text)
{
byte[] buffer = Encoding.UTF8.GetBytes(text);
var memoryStream = new MemoryStream();
using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Compress, true))
{
gZipStream.Write(buffer, 0, buffer.Length);
}
memoryStream.Position = 0;
var compressedData = new byte[memoryStream.Length];
memoryStream.Read(compressedData, 0, compressedData.Length);
var gZipBuffer = new byte[compressedData.Length + 4];
Buffer.BlockCopy(compressedData, 0, gZipBuffer, 4, compressedData.Length);
Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gZipBuffer, 0, 4);
return Convert.ToBase64String(gZipBuffer);
}
我的減壓方法:
public static string Decompress(string compressedText)
{
byte[] gZipBuffer = Convert.FromBase64String(compressedText);
using (var memoryStream = new MemoryStream())
{
int dataLength = BitConverter.ToInt32(gZipBuffer, 0);
memoryStream.Write(gZipBuffer, 4, gZipBuffer.Length - 4);
var buffer = new byte[dataLength];
memoryStream.Position = 0;
using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
{
gZipStream.Read(buffer, 0, buffer.Length);
}
return Encoding.UTF8.GetString(buffer);
}
}
測試您的壓縮/解壓縮是分開的數據庫存儲/檢索方式方法。他們的工作是否相互獨立? – prprcupofcoffee
我測試這些方法分開他們工作正常 – motevalizadeh
如果您將它存儲在二進制字段爲什麼你使用'Convert.ToBase64String(gZipBuffer);'?,你也使用'UTF8.GetBytes'而不是'ASCII.GetBytes' –