EmJay
EmJay

Reputation: 13

Converting an absolute pathname to something more personal

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

Answers (1)

Tim Schmelter
Tim Schmelter

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

Related Questions