转载自:http://blog.csdn.net/nickwar/article/details/4972673
#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