我遇到了一个非常简单的程序的问题。我们从这段工作代码开始:
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;
}
}
}