![](/img/trans.png)
[英]GZipStream works when writing to FileStream, but not MemoryStream
[英]MemoryStream VS FileStream which one is better to use in Webservice for GZipStream decompress?
我有一個asp.net網絡服務。 該Web服務的某些功能是首先解壓縮客戶端請求。 為此,我編寫了2種方法,一種使用MemoryStream ,另一種使用FileStream 。
當使用MemoryStream某些對象時,它將獲得OutofMemoryException 。 因此,出於這個原因,我計划使用FileStream代替MemoryStream。
在使用此功能之前,我只需要澄清一下我在為正確的工作做正確的事情。
N:B:我的客戶有時會將10MB以上的數據發送到Web服務,而我需要在Web服務端進行解壓縮。 我有200多個客戶端在運行。 盡管我的Web服務位於不同的應用程序池中,但在托管Web服務的地方還有30多個Web應用和Web服務。
我確實看到了: GZIP解壓縮C#OutOfMemory
我從那里獲得了一些知識,但是對於Web服務,哪一個更好,我根據自己的情況感到相當困惑。 我需要對此有一個清晰的了解。
解壓縮方法(使用MemoryStream)如下:
public static string Decompress(string compressedText)
{
try
{
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 = new byte[msgLength];
ms.Position = 0;
using (GZipStream zip = new GZipStream(ms, CompressionMode.Decompress))
{
zip.Read(buffer, 0, buffer.Length);
}
return Encoding.UTF8.GetString(buffer);
}
}
catch (Exception ex)
{
DataSyncLog.Debug(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType + "::" + System.Reflection.MethodBase.GetCurrentMethod().ToString() + ":" + ex.ToString()+" : "+ex.StackTrace);
}
return string.Empty;
}
解壓縮方法(使用FileStream)如下:
public static string Decompress(string compressedText)
{
string SourceDirectory = System.Guid.NewGuid().ToString();
string DestinationDirectory = System.Guid.NewGuid().ToString();
try
{
File.WriteAllBytes(SourceDirectory, Convert.FromBase64String(compressedText));
using (FileStream fd = File.Create(DestinationDirectory))
{
using (FileStream fs = File.OpenRead(SourceDirectory))
{
fs.Seek(4, 0);
using (Stream csStream = new GZipStream(fs, CompressionMode.Decompress))
{
byte[] buffer = new byte[1024];
int nRead;
while ((nRead = csStream.Read(buffer, 0, buffer.Length)) > 0)
{
fd.Write(buffer, 0, nRead);
}
}
}
}
return Encoding.UTF8.GetString(File.ReadAllBytes(DestinationDirectory));
}
catch (Exception ex)
{
DataSyncLog.Debug(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType + "::" + System.Reflection.MethodBase.GetCurrentMethod().ToString() + ":" + ex.ToString() + " : " + ex.StackTrace);
return string.Empty;
}
finally
{
ClearFiles(SourceDirectory);
ClearFiles(DestinationDirectory);
}
}
有人可以告訴我應該使用哪個正確的方向,或者可以對使用MemoryStream的方法進行必要的修改以克服此錯誤。 如果您對我或任何代碼更改建議有清晰的了解,我將不勝感激。
在第二種情況下,使用流在內存方面看起來更加高效:使用內存流,您可以將整個流保存在內存中,而使用文件流,則只能使用有限大小的緩沖區。
您的這兩種方法都可能由於其簽名而導致內存問題:當客戶端發送10MB內存時,該內存量將分配給CompressedText參數和返回值。
您可以查看服務接口的變化,以便按塊傳輸數據(在這里您可以找到類似方法的示例-http: //www.codeproject.com/Articles/43272/Uploading-Large-Files-Through-Web-服務 )
或者,如果您考慮切換到WCF,則它支持流傳輸模式-http://msdn.microsoft.com/zh-cn/library/ms751463.aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.