Reputation: 13
I have a pathname C:\Users\<user name>\Documents\Folder
returned from using the FileBrowserDialog, that I would prefer to display using the My Documents\Folder
.
Other than using
pathname.StartsWith(My.Computer.FileSystem.SpecialDirectories.MyDocuments)
to see if the pathname 'belongs' in My Documents, is there another way of converting the pathname to use My Documents
?
Upvotes: 0
Views: 50
Reputation: 460238
You could use this approach which loops the parent directories up to the root:
DirectoryInfo directory = new DirectoryInfo("C:\\Users\\Tim\\Documents\\Folder\\file.ext");
string myDocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
bool isMyDocs = directory.FullName == myDocs;
while (!isMyDocs && (directory = directory.Parent) != null)
isMyDocs = directory.FullName == myDocs;
// use your personal folder-name acc. to isMyDocs
Update:
I should re-phrase the question. I want to end up with shorthand path notation e.g. \My Documents\Folder\file.ext
I thought it would be clear:
string yourFile = "C:\\Users\\Tim\\Documents\\Folder\\file.ext";
string yourDir = Path.GetDirectoryName(yourFile);
DirectoryInfo directory = new DirectoryInfo(yourDir);
string myDocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
bool isMyDocs = directory.FullName == myDocs;
while (!isMyDocs && (directory = directory.Parent) != null)
isMyDocs = directory.FullName == myDocs;
string personalPath = yourDir;
if(isMyDocs)
{
personalPath = Path.Combine("My Documents", "Folder", Path.GetFileName(yourFile));
}
Upvotes: 1