close

嗨~ 我是 IG 雞湯工程師 歡迎大家追蹤我喔~

用API在作檔案傳輸的時候,通常都會用 byte[] 轉成 Base64編碼的字串之後再傳輸,

那又會要從Base64編碼的字串,存回原來個檔案格式,像是Zip txt pdf 等等檔案格式。

所以之間格式轉換的技巧是很常用到的也相當重要。

 

目錄:

1. File.WriteAllBytes 直接存入成原本檔案 最常用

2.MemoryStream 讀出裡面資料內容

 

1. File.WriteAllBytes 直接存入法

程式:

string B64file = " JVBERi0xLjUNCiW1tbQoxIDAgb2Fsb2cvUGwIFIvTGFuZyh… ";

//可以換上.txt 或是 zip 等等 就看看原本檔案類型就可以了~

string FileName = "儲存檔名"+".pdf";

string FilePath = "儲存路徑";

System.IO.File.WriteAllBytes(System.IO.Path.Combine(FilePath, FileName), Convert.FromBase64String(B64file));

image

 

2. base64 編碼的txt檔案->轉成byte[]後->轉成MemoryStream->讀出裡面文字

string B64txt = " JVBERi0xLjUNCiW1tbQoxIDAgb2Fsb2cvUGwIFIvTGFuZyh… ";

byte[] byte64txt = Convert.FromBase64String(B64txt);
System.IO.MemoryStream mstxt = new System.IO.MemoryStream(byte64txt);
StreamReader sr = new StreamReader(mstxt);

//讀取每一行
while (!sr.EndOfStream)
 {              
       string line = sr.ReadLine();
 }

 

arrow
arrow
    文章標籤
    Base64 C#
    全站熱搜

    阿駿 發表在 痞客邦 留言(0) 人氣()