本篇内容介绍了“怎么用C#实现文件与字符串互转”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
将文件与为字符串互转
开发工具: Visual Studio 2013
.NET Framework版本:4.5
//选择文件路径
private void btnPath_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
textBox1.Text = ofd.FileName;
}
}
//调用文件转base64
private void btnBase64_Click(object sender, EventArgs e)
{
textBox2.Text = FileToBase64String(textBox1.Text);
MessageBox.Show("成功");
}
//调用base64转文件
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("成功");
}
}
//文件转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转文件
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;
}
}
观察代码可以发现,其实在上一篇做压缩的时候,也是用到了base64,所以如果是单纯的要操作文件的,只需要对文件进行流操作即可。
“怎么用C#实现文件与字符串互转”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。