我在數據庫中有一個.zip文件(BLOB)。我想在我的API中檢索相同的內容。請找到下面的代碼片段。我可以下載一個zip文件,但無法解壓。解壓時出錯。使用C#Ado.net從數據庫下載.zip文件
public IHttpActionResult GetDownloadLetter()
{
DownloadDocument docInfo = blogicObj.DownloadLetter();
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(docInfo.Document.GetBuffer())
};
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = docInfo.DocumentName + ".zip"
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
var response = ResponseMessage(result);
return response;
}
public class DownloadDocument
{
public MemoryStream Document { get; set; }
public string DocumentType { get; set; }
public string DocumentName { get; set; }
}
public DownloadDocument DownloadDocument()
{
DownloadDocument letter = null;
try
{
letter = GetDummyDownload();
}
catch (Exception ex)
{
throw ex;
}
return letter;
}
public MemoryStream GetMemoryStream(SqlDataReader reader, int columnIndex)
{
using (MemoryStream stream = new MemoryStream())
{
long startIdx = 0;
byte[] buffer = new byte[256];
while (true)
{
long retBytes = reader.GetBytes(columnIndex, startIdx, buffer, 0, buffer.Length);
stream.Write(buffer, 0, (int)retBytes);
startIdx += retBytes;
if (retBytes != buffer.Length)
break;
}
return stream;
}
}
public DownloadDocument GetDummyDownload()
{
DownloadDocument letter = null;
string strQuery = "select * from [dbo].[documents] where id=1";
using (SqlConnection connection = new SqlConnection(connStr))
{
SqlCommand command = new SqlCommand(connStr);
command.CommandType = CommandType.Text;
command.CommandText = strQuery;
command.Connection = connection;
connection.Open();
SqlDataReader reader = command.ExecuteReader();
// Call Read before accessing data.
while (reader.Read())
{
letter = new DownloadDocument();
letter.Document = GetMemoryStream(reader, 4); //4 is for document column
letter.DocumentType = Convert.ToString(reader["DocumentType"]);
letter.DocumentName = Convert.ToString(reader["Name"]);
}
// Call Close when done reading.
reader.Close();
}
return letter;
}
那麼什麼是你所得到的錯誤..? – MethodMan
以下文件無法打開或者它不是有效的zip文件。 – thegautamnayak