문제

I have a a string for a path for a file my program reads data from. I want to improve the robustness and I recall seeing someone do .\blabla\blalbla\ but I'm finding it a bit hard to find a topic that explains how this work so I can implement it into my program.

My path (I'm aware that the naming isn't correct but it'd interfere with my property if I named it with a capital P)

private const string path = @"C:\Users\zain\Desktop\program_storage\AccountDatabase.txt";

I'd like it to be something like .\program_storage\AccountDatabase.txt (this doesn't work unfortunately) as it'd mean I can move the program around without having to change the string in the constants class.

Any and all help is appreciated

도움이 되었습니까?

해결책

You can use something like the following to store/read the file:

var dir = Path.Combine(Environment
    .GetFolderPath(Environment.SpecialFolder.ApplicationData), "MyProgram");
if(!Directory.Exists(dir))
    Directory.CreateDirectory(dir);
var path = Path.Combine(dir, "AccountDatabase.txt");

This will use or create a folder in the App_Data of your user account and then return the path to a file in that folder. See the Environment.SpecialFolder enum for other locations possible.

다른 팁

You can use the IsolatedStorageFile class in the System.IO.IsolatedStorage namespace to easily access a directory that is isolated for the application and user:

See the MSDN documentation for more information: http://msdn.microsoft.com/en-us/library/3ak841sy(v=vs.110).aspx

There is a good example on MSDN here

This provides a nice abstraction from the physical location on the hard disk, and supports both local and roaming user profiles.

Note -

if using a local profile then the physical location is still going to be the <SYSTEMDRIVE>\Users\<user>\AppData\Local directory (for windows Vista/7/8/server 2008), as per the other answer

Note 2 -

You can also use a static method on IsolatedStorageFile to obtain a machine-scoped store (All Users)

IsolatedStorageFile isoFile = IsolatedStorageFile.GetMachineStoreForApplication();

This gets you the <SYSTEMDRIVE>\Users\All Users\AppData\Local directory on Windows Vista or later

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top