DirectoryInfo.GetFiles 抛出未处理的 StackOverflowException
本文关键字:StackOverflowException 未处理 GetFiles DirectoryInfo | 更新日期: 2023-09-27 18:13:16
在我的下载文档应用程序中,当我遍历目录以获取文件详细信息并将文件重命名和移动到某个文件夹时,我得到了Stackoverflow Exception as Unhandled
我的代码是
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()
工作正常,但是当它下载一个或多个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();
上面的代码也导致了 Stackoverflow 异常
请尝试directory.EnumerateFiles()
而不是directory.GetFiles()
。然后,而不是.Count() > 0
使用 .Any()
.
它们的区别如下:
- 使用
EnumerateFiles
时,可以在返回整个集合之前开始枚举 FileInfo 对象的集合。 - 使用
GetFiles
时,必须等待返回整个 FileInfo 对象数组,然后才能访问该数组。因此,当您处理许多文件和目录时,枚举文件可以更有效。
从此 MSDN 页面: https://msdn.microsoft.com/en-us/library/4cyf24ss(v=vs.110(.aspx
您应该
检查TempDownloadFolder字符串值。对我来说,它工作正常。
在 bin/debug/Temp 项目目录中创建文件夹名称 Temp
public FileInfo GetNewestFile()
{
try
{
System.IO.DirectoryInfo directory = new DirectoryInfo(@"Temp");
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;
}
}