Reputation: 510
I have this code to get all the files from a folder and its sub-directories.
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));
}
but it returns the file paths like this: C:\Users\RANDOM\Desktop\TheSelectedFolder\SubFolder1\Subfolder2\file.txt How can i make it return only the name of the Selected Folder plus the path of the sub-directories? without the drive letter, username, etc.
Upvotes: 0
Views: 1368
Reputation: 2875
If you use
System.IO.Path.GetDirectoryName(filePath)
where
filePath = "C:\Users\RANDOM\Desktop\TheSelectedFolder\SubFolder1\Subfolder2\file.txt"
it should return
`"C:\Users\RANDOM\Desktop\TheSelectedFolder\SubFolder1\Subfolder2"`
From this you can then use a regular expression like @"^[a-zA-Z]\:\Users\[^]+\" to cut out the bit of the path you don't want.
Edit: now that my brain is in hear, I can see that the answer I'd give has already been given.
Path.Combine(Path.GetDirectoryName(selectedFolder),filePath.Replace(selectedFolder,String.Empty))
Upvotes: 0
Reputation: 33738
silliness = Path.Combine( Path.GetDirectoryName(fb.SelectedPath),
folder.Replace(fb.SelectedPath, String.Empty)
)
Upvotes: 1