博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#文件相关操作
阅读量:1823 次
发布时间:2019-04-25

本文共 3263 字,大约阅读时间需要 10 分钟。

打开文件,并返回文件路径

public string OpenFile(string strFilter)        {
string strFileName = string.Empty; OpenFileDialog openFile = new OpenFileDialog(); openFile.Filter = strFilter; openFile.FilterIndex = 1; if (openFile.ShowDialog() == DialogResult.OK) {
strFileName = openFile.FileName; } return strFileName; }

导出图片

public void ExportPic(PictureBox picBox)        {
SaveFileDialog saveFile = new SaveFileDialog(); saveFile.Filter = "图像文件(*.PNG)|*.PNG|所有文件(*.*)|*.*"; if (saveFile.ShowDialog() == DialogResult.OK) {
string fileName = saveFile.FileName; string strExtension = Path.GetExtension(fileName); switch (strExtension) {
case ".png": picBox.Image.Save(fileName, System.Drawing.Imaging.ImageFormat.Png); break; case ".PNG": picBox.Image.Save(fileName, System.Drawing.Imaging.ImageFormat.Png); break; case ".jpg": picBox.Image.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg); break; case ".jpeg": picBox.Image.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg); break; default: break; } } }

将文件转换为二进制

public byte[] FileToBytes(string filePath)        {
FileInfo fileInfo = new FileInfo(filePath); byte[] buffer = new byte[fileInfo.Length]; FileStream fs = fileInfo.OpenRead(); fs.Read(buffer, 0, Convert.ToInt32(fileInfo.Length)); fs.Close(); return buffer; }

将给定二进制流写入一个新文件

public void CreateFile(byte[] fileBuffer,string newFilePath)        {
if (File.Exists(newFilePath)) {
File.Delete(newFilePath); } FileStream fs = new FileStream(newFilePath, FileMode.CreateNew); BinaryWriter bw = new BinaryWriter(fs); bw.Write(fileBuffer, 0, fileBuffer.Length); bw.Close(); fs.Close(); }

字节转图像

public Image Bytes2Img(byte[] buffer)        {
MemoryStream ms = new MemoryStream(buffer); ms.Position = 0; Image img = Image.FromStream(ms); ms.Close(); return img; }

图片转字节

public byte[] Img2Bytes(Image img)        {
byte[] bytes = null; MemoryStream ms = new MemoryStream(); img.Save(ms, ImageFormat.Png); bytes = ms.GetBuffer(); ms.Close(); return bytes; }

从图片文件路径转字节

public byte[] ImgFile2Bytes(string strPicFile)        {
if (string.IsNullOrEmpty(strPicFile)) return null; byte[] bytes = null; MemoryStream ms = new MemoryStream(); Image img = Image.FromFile(strPicFile); img.Save(ms, ImageFormat.Png); bytes = ms.GetBuffer(); ms.Close(); return bytes; }

转载地址:http://phikf.baihongyu.com/

你可能感兴趣的文章
【vue系列】在Vue项目中使用Sass-----(scss)安装详解,新手跟着做即可
查看>>
elementui 表格上加小问号 鼠标移入提示文字
查看>>
layui富文本编辑器的使用
查看>>
laydate日期插件时间
查看>>
h5页面微信分享代码
查看>>
phpqrcode生成二维码及使用方法
查看>>
php获取指定日期的上一个月和下一个月的日期
查看>>
jsp脚本、jsp表达式、jsp声明三者的区别。
查看>>
python网页解析器
查看>>
linux安装svn并设置自启动
查看>>
svn常用命令
查看>>
python2网页采集案例
查看>>
svn的服务端配置
查看>>
python3 urllib和requests模块
查看>>
Axure常见的几种原型图
查看>>
svn的checkout与export的区别与使用
查看>>
js实现点击复制功能
查看>>
phpquery采集案例
查看>>
jsp内置对象request的常用方法
查看>>
javascript 0和-0
查看>>