在我的下載文件應用我收到Stackoverflow Exception as Unhandled
當我通過遍歷目錄來獲取文件的詳細信息和重命名&移動文件到某個文件夾我的代碼是DirectoryInfo.GetFiles拋出未處理StackOverflowException
public FileInfo GetNewestFile()
{
try
{
System.IO.DirectoryInfo directory = new DirectoryInfo(TempDownloadFolder);
FileInfo result = null;
var list = directory.GetFiles(); // Stackoverflow Exception occurs here
if (list.Count() > 0)
{
result = list.OrderByDescending(f => f.LastWriteTime).First();
}
return result;
}
catch (Exception ex)
{
throw ex;
}
}
即應用程序下載PDF
和MS-Word
文件從一個網站,如果它下載PDF
文件順序directory.GetFiles()
工作正常,但當它下載1個或多個PDF
文件,然後下載一個MS-Word
文件應用程序拋出System.Stackoverflow
異常。
當我重新啓動應用程序下載MS-Word
文件作爲其是在陣容的第一個文件它運作良好,只有等到以後幾個文件已被下載
至於另一MS-Word`文件出現後下載我所知的例外狀況是因爲巨大的內存分配,但我想不通爲什麼它不發生的PDF
文件,但只發生了MS-Word
文件
編輯:
我用了返回最新的文件上面的代碼是
return di.GetFiles()
.Union(di.GetDirectories().Select(d => GetNewestFile()))
.OrderByDescending(f => (f == null ? DateTime.MinValue : f.LastWriteTime))
.FirstOrDefault();
上面的代碼也導致異常#1
一個文件夾名稱溫度是否有其他應用程序/方法不斷寫TempDownloadFolder? – Martheen
@Martheen是的文件將被多次downloded到'TempDownloadFolder',但重命名後它將被移動到永久下載文件夾 – Rajesh
結合他的評論使用簡單的循環來獲取最新的文件的PeterB答案可以通過避免更新文件,並且只保留在內存上的最大兩個文件屬性 – Martheen