欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#實(shí)現(xiàn)文件與字符串互轉(zhuǎn)的方法詳解

 更新時(shí)間:2022年08月30日 16:49:10   作者:Csharp 小記  
這篇文章主要為大家詳細(xì)介紹了如何利用C#實(shí)現(xiàn)文件與字符串互轉(zhuǎn)效果,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)C#有一定幫助,需要的可以參考一下

嗯,就是BASE64,不用多想,本來計(jì)劃是要跟上一篇字符串壓縮一起寫的,用來實(shí)現(xiàn)將一個(gè)文件可以用json或者text等方式進(jìn)行接口之間的傳輸,為了保證傳輸效率,所以對(duì)生成的字符串進(jìn)行進(jìn)一步壓縮。但是由于不能上傳完整源代碼,所以就還是分開寫了,方便展示實(shí)現(xiàn)效果以及功能的單獨(dú)使用。

實(shí)現(xiàn)功能

將文件與為字符串互轉(zhuǎn)

開發(fā)環(huán)境

開發(fā)工具: Visual Studio 2013

.NET Framework版本:4.5

實(shí)現(xiàn)代碼

 //選擇文件路徑
 private void btnPath_Click(object sender, EventArgs e)
 {
     OpenFileDialog ofd = new OpenFileDialog();
     if (ofd.ShowDialog() == DialogResult.OK)
     {
         textBox1.Text = ofd.FileName;
     }
 }
 //調(diào)用文件轉(zhuǎn)base64
 private void btnBase64_Click(object sender, EventArgs e)
 {
     textBox2.Text = FileToBase64String(textBox1.Text);
     MessageBox.Show("成功");
 }
 //調(diào)用base64轉(zhuǎn)文件
 private void btnFile_Click(object sender, EventArgs e)
 {
     SaveFileDialog sfd = new SaveFileDialog();
     sfd.Filter = "文件|*" + textBox1.Text.Substring(textBox1.Text.LastIndexOf('.'));
     if (sfd.ShowDialog() == DialogResult.OK)
     {
         Base64StringToFile(textBox2.Text, sfd.FileName);
         MessageBox.Show("成功");
     }
 }
 
 //文件轉(zhuǎn)base64
 public string FileToBase64String(string path)
 {
     try
     {
         string data = "";
         using (MemoryStream msReader = new MemoryStream())
         {
             using (FileStream fs = new FileStream(path, FileMode.Open))
             {
                 byte[] buffer = new byte[1024];
                 int readLen = 0;
                 while ((readLen = fs.Read(buffer, 0, buffer.Length)) > 0)
                 {
                     msReader.Write(buffer, 0, readLen);
                 }
 
             }
             data = Convert.ToBase64String(msReader.ToArray());
         }
 
         return data;
     }
     catch (Exception ex)
     {
         throw ex;
     }
 
 }
 
 //base64轉(zhuǎn)文件
 public void Base64StringToFile(string base64String, string path)
 {
     try
     {
         using (MemoryStream stream = new MemoryStream(Convert.FromBase64String(base64String)))
         {
             using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
             {
                 byte[] b = stream.ToArray();
                 fs.Write(b, 0, b.Length);
             }
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }

實(shí)現(xiàn)效果

觀察代碼可以發(fā)現(xiàn),其實(shí)在上一篇做壓縮的時(shí)候,也是用到了base64,所以如果是單純的要操作文件的,只需要對(duì)文件進(jìn)行流操作即可。

到此這篇關(guān)于C#實(shí)現(xiàn)文件與字符串互轉(zhuǎn)的方法詳解的文章就介紹到這了,更多相關(guān)C# 文件字符串互轉(zhuǎn)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論