2013-05-09 102 views
0

我有这个代码来获取文件夹及其子目录中的所有文件。获取文件的根路径

FolderBrowserDialog fb = new FolderBrowserDialog(); 
      if (fb.ShowDialog() == DialogResult.OK) 
      { 
       foreach (string folder in System.IO.Directory.GetFiles(fb.SelectedPath, "*.*", System.IO.SearchOption.AllDirectories)) 
        listBox1.Items.Add(Path.GetFullPath(folder)); 
      } 

但它返回这样的文件路径: C:\用户\随机\桌面\ TheSelectedFolder \ SubFolder1 \ Subfolder2 \ file.txt的 我怎样才能使它返回选定的唯一名称文件夹加上子目录的路径?没有盘符,用户名等

回答

1
silliness = Path.Combine(Path.GetDirectoryName(fb.SelectedPath), 
          folder.Replace(fb.SelectedPath, String.Empty) 
         ) 
0

如果使用

System.IO.Path.GetDirectoryName(filePath)

其中

filePath = "C:\Users\RANDOM\Desktop\TheSelectedFolder\SubFolder1\Subfolder2\file.txt" 

它应该返回

`"C:\Users\RANDOM\Desktop\TheSelectedFolder\SubFolder1\Subfolder2"` 

从这个,那么你可以使用正则表达式,如@“^ [a-zA-Z] \:\用户\ [^] + \“删除你不想要的路径位。

编辑:现在我的大脑在听,我可以看到我给的答案已经给出。

Path.Combine(Path.GetDirectoryName(selectedFolder),filePath.Replace(selectedFolder,String.Empty)) 
+0

我要检索选定文件夹的唯一名称+它的路径的子文件夹没有**“C:\用户\随机\桌面\ ** – Adrao 2013-05-09 04:54:32