C# 我在读文件时做得对吗?

C# 我在读文件时做得对吗?,c#,asp.net,file,file-upload,.net-2.0,C#,Asp.net,File,File Upload,.net 2.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 pa

此代码试图读取文件,但出现错误

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

您做得不对:无论何时打开文件流,都必须处理它

这将实现以下目的:

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;
    }
使用
语句将为您调用
Dispose()
,即使引发异常也是如此

当然,还可以避免文件锁定


您应该在
中使用
FileStream
语句,以确保正确关闭和处置它:

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

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

相反

是否在任何地方关闭/处置文件流?答案在错误消息中。因为它实现了<代码> IDISPOSITION/CODE >考虑将它封装在一个使用块中。不确定这个代码是否是异常的原因,如您所看到的,在FielestRAME调用之前,异常会谈论一个StreamWriter,搜索您的代码试图写入该文件的内容。这是真的。保持简单@很好!考虑其他回答者和
File.ReadAllBytes
的用法。这也是一个很好的解决方案,但是如果您想检查文件被锁定的原因,对吧,您得到了答案!:)