C#實(shí)現(xiàn)文件與Base64的相互轉(zhuǎn)換
一.轉(zhuǎn)換工具:
二.Base64轉(zhuǎn)文件代碼:
這個(gè)案例是,將已經(jīng)獲取到的Base64字符串,轉(zhuǎn)換成文件,保存到服務(wù)器的某個(gè)文件路徑下面。
注意:案例中的Base64字符串:document.content不含有“data:application/pdf;base64,”之類的前綴,請(qǐng)自行用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前面會(huì)帶有“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#實(shí)現(xiàn)文件與Base64的相互轉(zhuǎn)換的文章就介紹到這了,更多相關(guān)C# 文件與Base64轉(zhuǎn)換內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#表達(dá)式中的動(dòng)態(tài)查詢?cè)斀狻咀g】
這篇文章主要給大家介紹了關(guān)于C#表達(dá)式中動(dòng)態(tài)查詢的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01C#實(shí)現(xiàn)把指定數(shù)據(jù)寫入串口
這篇文章主要介紹了C#實(shí)現(xiàn)把指定數(shù)據(jù)寫入串口,直接給出示例代碼,需要的朋友可以參考下2015-06-06深入C# winform清除由GDI繪制出來的所有線條或圖形的解決方法
本篇文章是對(duì)在C#中使用winform清除由GDI繪制出來的所有線條或圖形的方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05