Modify path string to improve robustness

泄露秘密 提交于 2019-12-17 17:07:11

问题


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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/23222837/modify-path-string-to-improve-robustness

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!