2013-06-11 72 views
0

我需要從我的asp.net mvc項目文件夾中選取一個excel文件並將其編碼爲base64字符串。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(); 
     } 

到目前爲止,這不正常。有什麼建議麼?

+0

究竟是什麼錯呢?它是否會拋出異常? – Maciej

+0

我的web服務拒絕/拒絕它,然後我再次將base64字符串轉換爲byte []並傳遞給方法。 – mat1c

+0

你能發佈錯誤細節嗎?你的意思是「我的webservice拒絕/拒絕它」 – Maciej

回答

0

ü可以嘗試:

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; 
    }