我遇到了一个非常简单的程序问题。我们开始了与该位工作代码: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;
}
}
}
不是你的问题的原因,但'FileStream'也需要在'using'块中。另外,什么是'RemoteFileInfo'类? – 2012-08-14 18:13:51
我用RemoteFileInfo的定义更新了这个问题,对不起,我以前没有包括这个。我刚刚意识到我也编辑过这个文件,编写处理对象,也许我的错误在那里。 – 2012-08-14 19:18:57
你是否从服务中返回'RemoteFileInfo'的实例? – 2012-08-14 19:22:01