2012-08-14 18 views
1

我遇到了一个非常简单的程序问题。我们开始了与该位工作代码:RemoteFileInfo因使用语句失败

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; 

这需要在一个名为包含文件名“请求”参数,我们检查文件是否存在,如果是这样,我们流的文件。

好了,通过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 

服用使用()语句出来,解决了这一问题,但我不明白为什么。通过添加代码,我认为我做了一件好事。我想了解我做错了什么,以便我不重复,并可以正确编写此方法。

这里是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; 
      } 

    } 
} 
+3

不是你的问题的原因,但'FileStream'也需要在'using'块中。另外,什么是'RemoteFileInfo'类? – 2012-08-14 18:13:51

+0

我用RemoteFileInfo的定义更新了这个问题,对不起,我以前没有包括这个。我刚刚意识到我也编辑过这个文件,编写处理对象,也许我的错误在那里。 – 2012-08-14 19:18:57

+0

你是否从服务中返回'RemoteFileInfo'的实例? – 2012-08-14 19:22:01

回答

0

如果你正在返回实现IDisposable的对象,那么你不能Dispose它。这必须由呼叫者决定。

+0

你是指我的RemoteFileInfo类的实现?有Dispose()?如果是这样,我很困惑,因为代码要求我实现一个配置,它不会编译没有它 – 2012-08-15 11:36:27

+0

它不会编译没有它,因为你有它在'使用'块。你需要摆脱'use'块。 – 2012-08-15 14:49:42

0

你要打电话给你的流Flush方法将纠正问题的定义。这是因为你在冲洗流之前做了处理,所以没有数据;-)

+0

我在返回之前调用'stream.Flush()',但没有帮助。我不认为这会有所帮助,因为我们需要返回流,而不是一次全部的数据。 – 2012-08-14 19:24:02