Home > Software design >  Parsing string containing Special Folder
Parsing string containing Special Folder

Time:09-16

I've allowed for custom paths to be entered and wanted the default to be something along the lines of: %UserProfile%/Documents/foo, of course this needs to successfully parse the string and though it will work in Windows Explorer, I was wondering if I'm missing a library call or option for parsing this correctly.

DirectoryInfo's constructor certainly doesn't work, treating %UserProfile% like any other folder name. If there is no good way, I'll manually parse it to substitute %foo% with the actual special folder location if it is in the Special Folders Enumeration.

Edit: Code that does what I'm looking for (though would prefer a proper .NET library call):

var path = @"%UserProfile%/Documents/foo";
var specialFolders = Regex.Matches(path, "%(?<possibleSpecial>. )%");
foreach (var spec in specialFolders.AsEnumerable())
{
    if (Enum.TryParse<Environment.SpecialFolder>(spec.Groups["possibleSpecial"].Value, out var sf))
    {
        path = Regex.Replace(path, spec.Value, Environment.GetFolderPath(sf));
    }
 }

CodePudding user response:

Use Environment.ExpandEnvironmentVariables on the path before using it.

var pathWithEnv = @"%UserProfile%/Documents/foo";
var path = Environment.ExpandEnvironmentVariables(pathWithEnv);
// your code...    
  • Related