Reputation: 15
I recently had to make a button in C# that simply had to open a text file. The job was easy until I realized that I had no ideea how to open the file, why? Well simply because I can't think of a way to "define" the user's name in the path to the file.
Here is the code I tryed to use:
private void button5_Click(object sender, EventArgs e)
{
try
{
System.Diagnostics.Process.Start("C:\\Users\\%USERNAME%\\AppData\\Roaming\\SchoolProject\\file.txt");
}
catch { }
}
And, it did not work.
So what's the solution to this problem? If you feel like knowing the answer please be very explicit about it, I'm new to programming languages and I don't quite understand the codes so well. ( If you can and if it's not too much to ask please include the code that should work in your answer.)
Upvotes: 0
Views: 3289
Reputation: 223267
You need to expand environment variable use: Environment.ExpandEnvironmentVariables
Replaces the name of each environment variable embedded in the specified string with the string equivalent of the value of the variable, then returns the resulting string.
Environment.ExpandEnvironmentVariables("C:\\Users\\%USERPROFILE%\\AppData\\Roaming\\SchoolProject\\file.txt");
This will give you the exact path.
So your code could be:
string filePath = Environment.ExpandEnvironmentVariables("C:\\Users\\%USERPROFILE%\\AppData\\Roaming\\SchoolProject\\file.txt");
System.Diagnostics.Process.Start(filePath);
Also, having an empty try-catch
will not help you in determining the exception, catch specific exception or at least base class Exception
and then you can log/look in the debugger, at the exception and its message.
Upvotes: 1
Reputation: 61349
You can get to all of these "special" folder locations via the Environment.SpecialFolders
enum and the GetFolderPath
method.
In your case, you want SpecialFolder.ApplicationData
. Something like:
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "test.txt");
All the special folders can be found on MSDN.
Upvotes: 1