简体   繁体   English

我在读取文件时做对了吗?

[英]Am I doing it right while reading a file?

This code is trying to read a file but giving error, 这段代码试图读取文件,但给出错误信息,

   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)

I think this is the code causing the problem while reading file, it works fine on development and integration servers but not on production server. 我认为这是导致读取文件时出现问题的代码,它在开发和集成服务器上正常工作,而在生产服务器上则无法正常工作。

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

Use: 采用:

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

Instead! 代替!

You should use FileStream inside using statement to ensure that it is properly closed and disposed: 您应该在using语句中使用FileStream以确保其已正确关闭和处置:

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

MSDN MSDN

You're not doing right: whenever you open a file stream, you must dispose it . 您做错了:每当打开文件流时, 都必须对其进行处置

This will do the trick: 这将达到目的:

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 statements will call Dispose() for you, even if an exception is thrown! 即使抛出异常, using语句也会为您调用Dispose()

And, of course, you'll avoid file locking. 而且,当然,您将避免文件锁定。

Take a look at this article. 看一下这篇文章。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM