【发布时间】:2012-05-27 06:03:45
【问题描述】:
我遇到了一个大问题,好吧,这就是问题所在: 我正在尝试从目录中获取文件信息,以便可以在 listview 上列出它。 当我使用该方法递归搜索文件时:
private void Get_Files(string path)
{
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] fi = di.GetFiles();
foreach (FileInfo Info in fi)
{
try
{
Files.Add(Info.FullName);
}
catch(Exception ee)
{
MessageBox.Show(ee.Message);
}
}
foreach (DirectoryInfo DInfo in di.GetDirectories())
{
Get_Files(DInfo.FullName);
}
}
有时路径长于 260 个字符,所以我收到该错误: 路径太长,不应该超过260个字符,我在互联网上搜索过,人们说它没有解决方案,但我自己想出了一个解决方案。 解决方案:正在创建一个字符串并将路径的每个路径附加到该字符串,因此在将整个路径保存到字符串时我永远不会遇到该错误。 把它想象成把路径分开,把每一块都附加到字符串上。 所以这是我想出的解决方案:
List<string> Files = new List<string>();
string completepath = string.Empty;
string current_dire_name = string.Empty;
private void Get_Files(string path)
{
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] fi = di.GetFiles();
foreach (FileInfo Info in fi)
{
try
{
completepath += "\\" + Info.Name;
Files.Add(completepath);
string remove_file_name = completepath;
remove_file_name = remove_file_name.Replace("\\" + Info.Name, "");
completepath = remove_file_name;
}
catch(Exception ee)
{
if(DialogResult.Yes == MessageBox.Show("Error at the Get_Files Method and Error message :\n\n" + ee.Message + "\n\nQuit Application now ?","",MessageBoxButtons.YesNo,MessageBoxIcon.Question))
{
Environment.Exit(0);
}
}
}
foreach (DirectoryInfo DInfo in di.GetDirectories())
{
string remove_folder_name = completepath;
remove_folder_name = remove_folder_name.Replace("\\" + current_dire_name, "");
completepath = remove_folder_name;
current_dire_name = DInfo.Name;
completepath += "\\" + DInfo.Name;
Get_Files(DInfo.FullName);
}
}
好的,那个方法救了我,但是它生成了错误的路径,我的意思是有些东西不正确,假设路径应该是:C:\Folder1\Folder2\Folder3\file.txt 生成的路径是: C:\Folder1\file.txt ,类似的东西.... 我知道我做的方法有问题,尤其是递归追加。
我希望有人和我一起弄清楚,这样人们就可以避免长路径异常。
【问题讨论】:
-
那是因为你的方法不对,反正也没用。
-
我知道方法有问题,这就是我想弄清楚的,也许如果有人分享更好的算法,那也会有帮助
-
没有这样的解决方法。
Get*()将在大于 260 个字符的字符串上失败,无论您如何构建字符串。
标签: c# .net algorithm exception-handling io