2013-03-21 56 views
0

此代碼試圖讀取一個文件,但給錯誤,我在閱讀文件時是否正確?

System.IO.IOException: The process cannot access the file 'C:\doc.ics' because it is being used by another process. 
    at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) 
    at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) 
    at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options) 
    at System.IO.StreamWriter.CreateFile(String path, Boolean append) 
    at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize) 
    at System.IO.StreamWriter..ctor(String path) 

我覺得這是在閱讀文件導致了問題的代碼,它工作正常的開發和集成服務器,但不是生產服務器上。

private byte[] ReadByteArrayFromFile(string fileName) 
    { 
     byte[] buffer = null; 
     FileStream filestrm = new FileStream(fileName, FileMode.Open, FileAccess.Read); 
     BinaryReader binaryread = new BinaryReader(filestrm); 
     long longNumBytes = new FileInfo(fileName).Length; 
     buffer = binaryread.ReadBytes((int)longNumBytes); 
     return buffer; 
    } 
+0

你關閉/處理文件流的任何地方?答案出現在錯誤消息中。由於它實現了'IDisposable',因此可以考慮將其封裝在一個使用塊中。 – DGibbs 2013-03-21 10:07:21

+0

不確定這段代碼是否是異常的原因,正如您所看到的,在FileStream調用之前,該異常說明了StreamWriter,搜索代碼嘗試寫入文件的位置。 – Steve 2013-03-21 10:08:55

回答

2

你沒有做正確的:每當你打開一個文件流,你必須處理它

這將這樣的伎倆:

private byte[] ReadByteArrayFromFile(string fileName) 
    { 
     byte[] buffer = null; 

     using(FileStream filestrm = new FileStream(fileName, FileMode.Open, FileAccess.Read)) 
     using(BinaryReader binaryread = new BinaryReader(filestrm)) 
     { 
      long longNumBytes = new FileInfo(fileName).Length; 
      buffer = binaryread.ReadBytes((int)longNumBytes); 
     } 

     return buffer; 
    } 

using報表將調用Dispose()你,即使有異常拋出!

而且,當然,你會避免文件鎖定。

Take a look at this article.

+0

歡呼起來吧 – Mathematics 2013-03-21 11:08:21

+0

@ user13814不錯!考慮其他回答者和'File.ReadAllBytes'的用法。這也是一個很好的解決方案,但如果你想查看文件被鎖定的原因,那麼你就有了答案! :) – 2013-03-21 11:09:18

3

您應該使用FileStreamusing聲明,以確保它是正確關閉和設置:

using (FileStream fs = File.OpenRead(path)) 
{ 
    ... 
} 

MSDN

5

用途:

var bytes = File.ReadAllBytes(@"path"); 

取而代之!

+0

這是真的。把事情簡單化! – 2013-03-21 10:11:15

+0

它也可以與.net 2.0一起使用 – Mathematics 2013-03-21 11:08:02

相關問題