C# System.IO.FileStream 读取被其他程序打开的文件提示“文件正由另一进程使用,因此该进程无法访问该文件。”...

#region 将二进制转化为文件 public static string ConvertByteToFile(object objData, string filePathName) { //string fileName = ""; //fileName = new PublicConst().PathTempFile + fileName; string folder = System.IO.Path.GetDirectoryName(filePathName); if (!System.IO.Directory.Exists(folder)) { System.IO.Directory.CreateDirectory(folder); } if (System.IO.File.Exists(filePathName)) { try { System.IO.File.Delete(filePathName); } catch { //("FileInUse"); return ""; } } System.IO.FileStream fs = new System.IO.FileStream(filePathName, System.IO.FileMode.Create, System.IO.FileAccess.Write); System.IO.BinaryWriter w = new System.IO.BinaryWriter(fs); try { w.Write(objData as byte[]); } catch (Exception) { } finally { w.Close(); fs.Close(); } return filePathName; } #endregion 将文件转化为二进制代码时,出现提示:

文件正由另一进程使用,因此该进程无法访问该文件

原来是构造System.IO.FileStream时,使用的方法有问题

一开始是直接使用

System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open)

这个方法打开文件的时候是以只读共享的方式打开的,但若此文件已被一个拥有写权限的进程打开的话,就无法读取了,

因此需要使用

System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open,System.IO.FileAccess.Read,FileShare.ReadWrite);

设置文件共享方式为读写,FileShare.ReadWrite,这样的话,就可以打开了

附,把二进制转化为文件的函数

这两个函数经常用来存取数据库哦的BLOB字段。

#region 将文件转化为二进制 public static byte[] ConvertFileToByte(string fileName) { if (!System.IO.File.Exists(fileName)) { return null; } System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open,System.IO.FileAccess.Read,FileShare.ReadWrite); byte[] nowByte = new byte[(int)fs.Length]; try { fs.Read(nowByte, 0, (int)fs.Length); return nowByte; } catch (Exception) { return null; } finally { fs.Close(); } } #endregion

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值