Recursively append directory names to a string
i got a big problem , alright so here is the problem : I am trying to get the fileinfo from a directory so that i can list it on listview . When i recursively search for files using that method :
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);
}
}
Sometimes the path is longer than 260 Characters , so i am getting that error : Path is too long and it should not exceed 260 Characters , i have searched over the internet and people said that it has no solution , but i have figured out a solution my self . Solution : is creating a string and appending each path of the path to that string , so i never get that error when saving the whole path into string. Think of it as taking the path apart and taking each piece and appending it to the string. So here is the solution i figured :
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 :nn" + ee.Message + "nnQuit 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);
}
}
Okay , that method saved me , but it generated wrong path , i mean something is not correct , lets say if path should be : C:Folder1Folder2Folder3file.txt The generated path is : C:Folder1file.txt , something like that .... I know that the method i did has something wrong especially the recursive appending.
I hope someone figure it with me , so that people can avoid the long path exception.
您正在寻找.Net Long Path库,它使用Windows API的?
前缀来完全避免限制。
上一篇: 无法访问IIS元数据库
下一篇: 将目录名递归追加到字符串