RemoteFileInfo失败,使用Using语句

时间:2012-08-14 18:08:50

标签: c# using

我遇到一个非常简单的程序问题。我们从这段工作代码开始:

RemoteFileInfo result = new RemoteFileInfo();

string filePath = System.IO.Path.Combine(ConfigurationManager.AppSettings["OmnitureSPDir"], request.FileName);
System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);

// check if exists
if (!fileInfo.Exists)
    throw new System.IO.FileNotFoundException("File not found",
                      request.FileName);

// open stream
System.IO.FileStream stream = new System.IO.FileStream(filePath,
          System.IO.FileMode.Open, System.IO.FileAccess.Read);

// return result 
result.FileName = request.FileName;
result.Length = fileInfo.Length;
result.FileByteStream = stream;

return result;

这会引入一个名为“request”的参数,其中包含文件名,我们会检查文件是否存在,如果存在,我们会传输文件。

好吧,在完成Visual Studio中的微软代码分析并注意到没有dispose()后,我通过将其包装在using语句中来“解决”了这个问题:

using (RemoteFileInfo result = new RemoteFileInfo()) {

    string filePath = System.IO.Path.Combine(ConfigurationManager.AppSettings["OmnitureSPDir"], request.FileName);
    System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);

    // check if exists
    if (!fileInfo.Exists)
        throw new System.IO.FileNotFoundException("File not found",
                          request.FileName);

    // open stream
    System.IO.FileStream stream = new System.IO.FileStream(filePath,
              System.IO.FileMode.Open, System.IO.FileAccess.Read);

    // return result 
    result.FileName = request.FileName;
    result.Length = fileInfo.Length;
    result.FileByteStream = stream;

    return result;
}

运行此代码后,我们发现该文件不再流式传输,但会出错:

Value cannot be null.
Parameter name: FileByteStream

取出Using()语句,解决了问题,但我不明白为什么。通过添加代码,我以为我做了一件好事。我想了解我做错了什么,所以我不重复它并且可以正确编码这个方法。

这是RemoteFileInfo

的定义
public class RemoteFileInfo : IDisposable
{
    [MessageHeader(MustUnderstand = true)]
    public string FileName;

    [MessageHeader(MustUnderstand = true)]
    public long Length;

    [MessageBodyMember(Order = 1)]
    public System.IO.Stream FileByteStream;

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);

    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing && FileByteStream != null)
            {
                FileByteStream.Close();
                FileByteStream = null;
            }

    } 
}

2 个答案:

答案 0 :(得分:0)

您必须在流中调用Flush方法才能解决问题。这是因为你在刷新你的流之前进行了一次处理,所以没有数据; - )

答案 1 :(得分:0)

如果要返回实现IDisposable的对象,则不能Dispose它。这必须取决于来电者。