C# Open File, Path Starting with %Userprofile%

c# open file, path starting with %userprofile%

Use Environment.ExpandEnvironmentVariables on the path before using it.

var pathWithEnv = @"%USERPROFILE%\AppData\Local\MyProg\settings.file";
var filePath = Environment.ExpandEnvironmentVariables(pathWithEnv);

using(ostream = new FileStream(filePath, FileMode.Open))
{
//...
}

Process.Start - Directory - Instead of %userprofile%

I believe you are looking for this:

Environment.SpecialFolder.Desktop

The logical Desktop rather than the physical file system location.

Which combined with Environment.GetFolderPath returns:

The path to the specified system special folder

So you should use it like this:

string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
Process.Start(Path.Combine(desktop, "She's here", "She's here..lnk"));

Opening a file by passing in absolute file path

If you are operating with paths like file:/{absolute path} (which is actually an URI)
you may use System.Uri class.

As in this answer.

var uri = new Uri("file:/Users/km/Downloads/PT07E.obj");
using (var reader = File.OpenText(uri.AbsolutePath))
{
...
}

Using the user's username as path for opening a file

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.

C#: How to make a string with a path of the Current User's directory?

Your User profile path stores in

Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)

To get specifc file path from that Folder you need to combine it with hard coded string of your file name, like

 string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "file.txt")

Output:

enter image description here

Note: Do not forget to add using System.IO because Path class is present in System.IO

How to get a path to the desktop for current user in C#?

string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

C# File Disappeared after FileInfo.MoveTo with Local Path (Windows)

It should be in project folder. Usually files without specefying path are saved there. (in folder with .exe file)



Related Topics



Leave a reply



Submit