Am I doing it right while reading a file?

此生再无相见时 提交于 2019-12-13 04:29:19

问题


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

回答1:


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!

And, of course, you'll avoid file locking.

Take a look at this article.




回答2:


Use:

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

Instead!




回答3:


You should use FileStream inside using statement to ensure that it is properly closed and disposed:

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

MSDN



来源:https://stackoverflow.com/questions/15544432/am-i-doing-it-right-while-reading-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!