我遇到了一個非常簡單的程序問題。我們開始了與該位工作代碼: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