C#實現(xiàn)文件與Base64的相互轉(zhuǎn)換
更新時間:2023年06月27日 11:28:38 作者:黃瓜炒雞蛋兒
本文主要介紹了C#實現(xiàn)文件與Base64的相互轉(zhuǎn)換,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
一.轉(zhuǎn)換工具:
二.Base64轉(zhuǎn)文件代碼:
這個案例是,將已經(jīng)獲取到的Base64字符串,轉(zhuǎn)換成文件,保存到服務(wù)器的某個文件路徑下面。
注意:案例中的Base64字符串:document.content不含有“data:application/pdf;base64,”之類的前綴,請自行用Substring等方法剔除。
//documents是系統(tǒng)自定義的類,里面包含了文件類型:imageFormat,Base64字符串:content public void SaveDocument(Documents document) { string sFilePath = "服務(wù)器文件路徑" + "\\Documents"; //創(chuàng)建路徑文件夾 string sFileName = "文件名字"+ "." + document.imageFormat.ToLower(); //這里的imageFormat就是文件類型 sFileName = sFilePath + "\\" + sFileName; //路徑不存在,則創(chuàng)建路徑 if (!Directory.Exists(sFilePath)) { Directory.CreateDirectory(sFilePath); } //如果文件已經(jīng)存在,則刪除文件 if (System.IO.File.Exists(sFileName)) { System.IO.File.Delete(sFileName); } //注意:文件直接轉(zhuǎn)base64前面會帶有“data:application/pdf;base64,”前綴,需要去掉。 byte[] DocBytes = Convert.FromBase64String(document.content); //文件流創(chuàng)建文件內(nèi)容 FileStream fs = new FileStream(sFileName, FileMode.CreateNew); BinaryWriter bw = new BinaryWriter(fs); bw.Write(DocBytes, 0, DocBytes.Length); bw.Close(); fs.Close(); }
三.文件轉(zhuǎn)Base64代碼:
? ? //文件全路徑:fileName ? ? public string DocumentToBase64Str(string fileName) ? ? { ? ? ? ? ? ? FileStream filestream = new FileStream(fileName, FileMode.Open); ? ? ? ? ? ? byte[] bt = new byte[filestream.Length]; ? ? ? ? ? ? //調(diào)用read讀取方法 ? ? ? ? ? ? filestream.Read(bt, 0, bt.Length); ? ? ? ? ? ? string base64Str = Convert.ToBase64String(bt); ? ? ? ? ? ? filestream.Close(); ? ? ? ? ? ? return base64Str; ? ? }
到此這篇關(guān)于C#實現(xiàn)文件與Base64的相互轉(zhuǎn)換的文章就介紹到這了,更多相關(guān)C# 文件與Base64轉(zhuǎn)換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
深入C# winform清除由GDI繪制出來的所有線條或圖形的解決方法
本篇文章是對在C#中使用winform清除由GDI繪制出來的所有線條或圖形的方法進行了詳細的分析介紹,需要的朋友參考下2013-05-05