- #region 將二進(jìn)制轉(zhuǎn)化為文件
- 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
將文件轉(zhuǎn)化為二進(jìn)制代碼時(shí),出現(xiàn)提示:
文件正由另一進(jìn)程使用,因此該進(jìn)程無法訪問該文件
原來是構(gòu)造System.IO.FileStream時(shí),使用的方法有問題
一開始是直接使用
System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open)
這個(gè)方法打開文件的時(shí)候是以只讀共享的方式打開的,但若此文件已被一個(gè)擁有寫權(quán)限的進(jìn)程打開的話,就無法讀取了,
因此需要使用
System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open,System.IO.FileAccess.Read,FileShare.ReadWrite);
設(shè)置文件共享方式為讀寫,F(xiàn)ileShare.ReadWrite,這樣的話,就可以打開了
附,把二進(jìn)制轉(zhuǎn)化為文件的函數(shù)
這兩個(gè)函數(shù)經(jīng)常用來存取數(shù)據(jù)庫哦的BLOB字段。
- #region 將文件轉(zhuǎn)化為二進(jìn)制
- 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
|