c#web api返回整个文件而不是字节数组

时间:2018-06-11 02:47:11

标签: c# file asp.net-web-api

对于我当前的web api,我返回一个文件作为byte [],它通过以下代码工作。

[Route("GetReferenceFile")]
    [HttpPost]
    public HttpResponseMessage GetReferenceFile([FromBody]ReferenceFileMonitorRetrievingRequest request)
    {
        try
        {
            var fileName = request.fileName;
            //get file path
            var filePathWoFileName = _manager.GetReferenceFileForReferenceFileMonitor(request.fileName, request.fileFolderPathWithFileName);
            //convert file into bytes array
            var dataBytes = File.ReadAllBytes(filePathWoFileName + request.fileName);
            //add bytes to memory stream 
            var dataStream = new MemoryStream(dataBytes);
            //send out
            HttpResponseMessage httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
            httpResponseMessage.Content = new StreamContent(dataStream);
            httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
            httpResponseMessage.Content.Headers.ContentDisposition.FileName = fileName;
            httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");

            return httpResponseMessage;
        }
        catch (IOException e)
        {
            logger.Error("Error Message: " + e.Message + " Stack Trace: " + e.StackTrace);
            return Request.CreateResponse(HttpStatusCode.InternalServerError, e);
        }
        catch (Exception ex)
        {
            logger.Error("Error Message: " + ex.Message + " Stack Trace: " + ex.StackTrace);
            return Request.CreateResponse(HttpStatusCode.InternalServerError, ex);
        }

请问有没有其他方法可以将整个文件发送出来而不是将文件作为byte []读取并发送过来?因为我害怕读取byte []可能会稍微改变文件,例如:“Tab”所做的空格可能不会保持不变。

提前谢谢你。

编辑:

我使用System.Text.Encoding.UTF8.GetString(// byte array)将字节数组转换为字符串并写入文件。这会引起任何改变原始文件内容的担忧吗?谢谢。

public async Task<string> GetReferenceFile(ReferenceFileRequest referenceFileRequest)
    {
        ConfigurationManager.RefreshSection("appSettings");
        var URL = ConfigurationManager.AppSettings["GetReferenceFile"];
        byte[] refFile = new byte[0];
        try
        {
            Client.DefaultRequestHeaders.Accept.Clear();
            Client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = await Client.PostAsJsonAsync(URL, referenceFileRequest);

            refFile = await response.Content.ReadAsByteArrayAsync();
            return System.Text.Encoding.UTF8.GetString(refFile); //Convert to string
        }
        catch (Exception ex)
        {
            logData.LogError("Error Message: " + ex.Message + " Stack Trace: " + ex.StackTrace);
            return null;
        }
    }

1 个答案:

答案 0 :(得分:2)

解决您的问题:字节是.NET使用标准IO代码读取文件的最低级别。读取字节时,您将读取原始文件数据。如果它是EXE,Word文档或文本文件并不重要。当您开始尝试使用错误的编码尝试在字节和文本之间进行转换时,可能会出现您描述的问题。既然你在这里没有做过类似的事情,你应该没有问题。

但是,您可以进行优化。此刻,您将整个文件读入内存。您可以将文件直接传送到响应。

替换此代码:

null

有了这个:

var dataBytes = File.ReadAllBytes(filePathWoFileName + request.fileName);
//add bytes to memory stream 
var dataStream = new MemoryStream(dataBytes);
//send out
HttpResponseMessage httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
httpResponseMessage.Content = new StreamContent(dataStream);