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;
    }
4

3 回答 3

5

采用:

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

反而!

于 2013-03-21T10:10:51.787 回答
3

您应该使用FileStreaminsideusing语句来确保它被正确关闭和处置:

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

MSDN

于 2013-03-21T10:08:50.857 回答
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;
    }

usingDispose()即使抛出异常,语句也会调用您!

而且,当然,您将避免文件锁定。

看看这篇文章。

于 2013-03-21T10:07:56.913 回答