[英]How to recreate a Zip File from a MemoryStream
我一直在尋找解決問題的方法,但似乎沒有人針對我要實現的目標。
我的問題是這樣的,我在Azure Blob存儲中存儲了Zip文件,為了安全起見,現在我們有一個API2控制器操作來配置這些zip文件,而不是允許直接下載。 此操作將檢索Blob,並將其下載到流中,以便可以將其打包在HTTPResponseMessage
。
上述所有工作均有效,但是,當我嘗試重新創建zip文件時,得知它已損壞。 現在,我只是嘗試讓服務器(在localhost上運行)創建zip文件,而最終目標是讓遠程客戶端應用程序執行此操作(我很確定服務器上的問題的解決方案是相同的。
public class FileActionResult : IHttpActionResult
{
private HttpRequestMessage _request;
private ICloudBlob _blob;
public FileActionResult(HttpRequestMessage request, ICloudBlob blob)
{
_request = request;
_blob = blob;
}
public async Task<HttpResponseMessage> ExecuteAsync(System.Threading.CancellationToken cancellationToken)
{
var fileStream = new MemoryStream();
await _blob.DownloadToStreamAsync(fileStream);
var byteTest = new byte[fileStream.Length];
var test = fileStream.Read(byteTest, 0, (int)fileStream.Length);
try
{
File.WriteAllBytes(@"C:\testPlatFiles\test.zip", byteTest);
}
catch(ArgumentException ex)
{
var a = ex;
}
var response = _request.CreateResponse(HttpStatusCode.Accepted);
response.Content = new StreamContent(fileStream);
response.Content.Headers.ContentLength = _blob.Properties.Length;
response.Content.Headers.ContentType = new MediaTypeHeaderValue(_blob.Properties.ContentType);
//set the fileName
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = _blob.Name,
Size = _blob.Properties.Length
};
return response;
}
}
我研究了Zip庫,看是否存在將zip流轉換回zip文件的解決方案,但是我所能找到的只是將zip文件讀入流,或者是為了提供文件下載而創建的文件創建。
任何幫助將不勝感激,謝謝。
您使用DotNetZip
。 它的ZipFile
類具有靜態工廠方法,該方法應該執行您想要的操作: ZipFile.Read( Stream zipStream )
將給定的流作為zip文件讀取,並為您提供ZipFile
實例(您可以將其用於任何用途)。
但是,如果您的Stream
包含原始zip數據,而您要做的只是將其持久化到磁盤,則您應該能夠直接將字節寫入磁盤。
如果遇到“ zip文件損壞”錯誤,我將查看用於將數據發送到Azure的內容編碼以及將其發送回的內容編碼。 您應該使用application/zip
或application/octet-stream
的內容類型將其發送到Azure,並可能將元數據添加到Azure blob條目中以相同的方式向下發送。
編輯要注意: DotNetZip曾經居住在Codeplex。 Codeplex已關閉。 舊的存檔仍可在Codeplex上獲得 。 看起來代碼已遷移到Github:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.