the file you are trying to open is in a different format than specified by the file extension in Asp.Net

后端 未结 4 977
我在风中等你
我在风中等你 2020-11-30 04:36

the file you are trying to open is in a different format than specified by the file extension c# error when trying to open file in excel.

Here is my code



        
4条回答
  •  抹茶落季
    2020-11-30 04:49

    In case someone else stumbles across this... I needed to convert blobs back into files on-the-fly in C#. Pdf's worked well and excel gave me this same error as OP explains.

    This is the code I wrote which handles excel differently from other file types.

    Giving excel application/octet-stream with an actual filename solved my issue. Probably not the cleanest way to do it but it was good enough for my purposes.

    string theExt = Path.GetExtension(theDoc.documentFileName).ToUpper();
    
    Response.Clear();
    
    if (theExt == ".XLS" || theExt == ".XLSX"){
        Response.ContentType = "application/octet-stream";
        Response.AddHeader("Content-Disposition", string.Format("inline; filename={0}", theDoc.documentFileName));
        }
    else{
        Response.ContentType = theDoc.documentMimeType;
        Response.AddHeader("Content-Disposition", string.Format("inline; filename={0}", theDoc.documentTitle));
    }
    
    using (MemoryStream stream = new MemoryStream(theDoc.file))
    {
        stream.WriteTo(Response.OutputStream);
        stream.Close();
    };
    
    Response.End();
    

提交回复
热议问题