'Why can't I set %USERPROFILE% for downloads in my C# project?
I am working on a program that retrieves files for the user from the internet. When I set the download path, either nothing happens, or Visual Studio tells me my path cannot be written to. Here are paths that I have tried:
(@"%USERNAME%\Downloads\");
(@"%USERPROFILE%\Downloads\");
(@"C:\Users\%USERNAME%\Downloads\");
(@"C:\Users\%USERPROFILE%\Downloads\");
What's even stranger is that using (@"%USERPROFILE%\Downloads\"); puts the downloaded files to the same folder as the program folder within a folder called %USERPROFILE%. I have used %USERPROFILE% in batch scripting before with no issues, is it a different wildcard in C#? What am I missing here?
Solution 1:[1]
C# does not automatically expand environment variables from strings. Doing so could have serious security implications among other issues.
You need to use the Environment.ExpandEnvironmentVariables method before attempting the file operation, for example something like;
using system;
void Main()
{
String DownloadPath= @"%USERPROFILE%\Downloads\";
String ExpandedDownloadPath = Environment.ExpandEnvironmentVariables(DownloadPath);
Console.WriteLine("ExpandedPath: {0}", ExpandedDownloadPath);
}
Obviously this is more a StackOverflow (programming) question
Solution 2:[2]
%Variablename% is batch syntax. In c# you have to resolve the environment variables manually.
See https://msdn.microsoft.com/de-de/library/77zkk0b6(v=vs.110).aspx
Solution 3:[3]
I use:
String DownloadPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\Downloads";
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gareth |
| Solution 2 | Franz |
| Solution 3 | The incredible Jan |
