此代碼試圖讀取一個文件,但給錯誤,我在閱讀文件時是否正確?
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;
}
你關閉/處理文件流的任何地方?答案出現在錯誤消息中。由於它實現了'IDisposable',因此可以考慮將其封裝在一個使用塊中。 – DGibbs 2013-03-21 10:07:21
不確定這段代碼是否是異常的原因,正如您所看到的,在FileStream調用之前,該異常說明了StreamWriter,搜索代碼嘗試寫入文件的位置。 – Steve 2013-03-21 10:08:55