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

FileStream内部ステートメントを使用usingして、適切に閉じて破棄されるようにする必要があります。

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 に答える