Ben
Ben

Reputation: 2523

Get a file path C#

I have a .txt file that I need to read in my program. For the moment I have the directory hardcoded as such:

file = new StreamReader(@"C:\Users\<username>\Documents\File.txt");

However that will (obviously) not work on any other PC that does not have that access to altering the code, or (by some strange happenstance) the same directory as the original code.

How can I get the full file path to set it in my program using C#?

Upvotes: 1

Views: 3955

Answers (2)

Hassan
Hassan

Reputation: 5430

Option 1:

Application.StartupPath can be used for the purpose.

It gets the path for the executable file that started the application, not including the executable name.

Keep File.txt with your executable.

Option 2:

Use Environment.SpecialFolder.ApplicationData

It gives directory that serves as a common repository for application-specific data for the current roaming user.

NOTE: If you want to restrict the user to look into the contents of File.txt then you might need to encrypt the contents.

Upvotes: 1

Grant Winney
Grant Winney

Reputation: 66449

You could create the file in their Application Data directory (they could still find it if they wanted to, but at least it wouldn't be as obvious as the My Documents folder).

When you want to access it, use the Environment class. There are methods for locating special folders for the current user, without resorting to hard-coded paths:

var filePath = Path.Combine(Environment.GetFolderPath(
                   Environment.SpecialFolder.ApplicationData), "File.txt");

Upvotes: 2

Related Questions