C# asp.net mvc将excel文件转换(编码)为base64字符串

C# asp.net mvc将excel文件转换(编码)为base64字符串,c#,asp.net,asp.net-mvc,asp.net-mvc-4,encoding,C#,Asp.net,Asp.net Mvc,Asp.net Mvc 4,Encoding,我需要从asp.net mvc项目文件夹中提取一个excel文件,并将其编码为base64字符串 现在的地雷代码: string base64 = String.Empty; var pathName = Server.MapPath("~/App_Data/ImportTemplate.xlsx");` byte[] docBytes = null; using (StreamReader strm = new StreamReader(pathName, System.Text.En

我需要从asp.net mvc项目文件夹中提取一个excel文件,并将其编码为base64字符串

现在的地雷代码:

 string base64 = String.Empty;
 var pathName = Server.MapPath("~/App_Data/ImportTemplate.xlsx");`
 byte[] docBytes = null;

using (StreamReader strm = new StreamReader(pathName, System.Text.Encoding.UTF8))
        {
            Stream s = strm.BaseStream;
            BinaryReader r = new BinaryReader(s);
            docBytes = r.ReadBytes(Convert.ToInt32(r.BaseStream.Length));
            base64 = Convert.ToBase64String(docBytes);
            r.Close();
            s.Close();
            strm.Close();
        }

到目前为止,这还不能正常工作。有什么建议吗

最可能的问题是base64数据包含“+”和“/”字符,这些字符是由HTTP专门解释的。您需要将该二进制文件转换为他们所谓的base64 URL编码,该编码对这些字符使用“-”和“-”。上的示例表明情况就是这样

有关如何进行转换的信息,请参阅。

您可以试试:

 byte[] docBytes = ReadFile(pathName);


 byte[] ReadFile(string sourcePath)
    {
        byte[] data = null;
        FileInfo fileInfo = new FileInfo(sourcePath);
        long numBytes = fileInfo .Length;
        FileStream fileStream = new FileStream(sourcePath, FileMode.Open, FileAccess.Read);
        BinaryReader br = new BinaryReader(fileStream);
        data = br.ReadBytes((int)numBytes);
        fileStream .Close();
        return data;
    }

到底是怎么回事?它是否引发异常?我的Web服务拒绝/拒绝它,然后我再次将base64字符串转换为byte[]并传递给方法。您可以发布错误详细信息吗?“我的Web服务拒绝/拒绝”是什么意思单击ViewDetails,您的请求可能太大了。查看
文件。ReadAllBytes(路径名)