0

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));
    }
 }
TobyL
  • 3
  • 3
  • `Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),"Documents","foo")`. I'm not sure what you asking exactly but this code give you the path – AliReza Sabouri Sep 14 '21 at 10:27
  • Only works for a specific, guaranteed special folder. Looking to parse folder paths containing special Folders – TobyL Sep 14 '21 at 10:28

1 Answers1

1

Use Environment.ExpandEnvironmentVariables on the path before using it.

var pathWithEnv = @"%UserProfile%/Documents/foo";
var path = Environment.ExpandEnvironmentVariables(pathWithEnv);
// your code...    
Sebastian Siemens
  • 2,302
  • 1
  • 17
  • 24