基本信息
文件名称:C#实现文件与Base64的相互转换.docx
文件大小:15.84 KB
总页数:2 页
更新时间:2025-05-21
总字数:约1.56千字
文档摘要

C#实现文件与Base64的相互转换

目录一.转换工具:二.Base64转文件代码:三.文件转Base64代码:

一.转换工具:

1.在线图片转Base64编码

2.BeJson在线JSON校验格式化工具

3.Base64在线加密,解密

二.Base64转文件代码:

这个案例是,将已经获取到的Base64字符串,转换成文件,保存到服务器的某个文件路径下面。

注意:案例中的Base64字符串:document.content不含有data:application/pdf;base64,之类的前缀,请自行用Substring等方法剔除。

//documents是系统自定义的类,里面包含了文件类型:imageFormat,Base64字符串:content

publicvoidSaveDocument(Documentsdocument)

stringsFilePath=服务器文件路径+\\Documents;//创建路径文件夹

stringsFileName=文件名字+.+document.imageFormat.ToLower();//这里的imageFormat就是文件类型

sFileName=sFilePath+\\+sFileName;

//路径不存在,则创建路径

if(!Directory.Exists(sFilePath))

Directory.CreateDirectory(sFilePath);

//如果文件已经存在,则删除文件

if(System.IO.File.Exists(sFileName))

System.IO.File.Delete(sFileName);

//注意:文件直接转base64前面会带有“data:application/pdf;base64,”前缀,需要去掉。

byte[]DocBytes=Convert.FromBase64String(document.content);

//文件流创建文件内容

FileStreamfs=newFileStream(sFileName,FileMode.CreateNew);

BinaryWriterbw=newBinaryWriter(fs);

bw.Write(DocBytes,0,DocBytes.Length);

bw.Close();

fs.Close();

}

三.文件转Base64代码:

??//文件全路径:fileName

??publicstringDocumentToBase64Str(stringfileName)

??{

??????FileStreamfilestream=newFileStream(fileName,FileMode.Open);

??????byte[]bt=newbyte[filestream.Length];

??????//调用read读取方法

??????filestream.Read(bt,0,bt.Length);

??????stringbase64Str=Convert.ToBase64String(bt);

??????filestream.Close();

??????returnbase64Str;

??}