修改路径字符串,以提高耐用性 [英] Modify path string to improve robustness
问题描述
我有一个文件,我的程序从读取数据的一种路径字符串。我想提高稳健性,我记得看到有人这样做。\\布拉布拉\\ blalbla \\但我发现它有点难以找到一个主题,介绍了如何这项工作,所以我可以实现它变成我的计划。
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.
我的路径(我知道的命名是不正确的,但它会与我的财产干扰,如果我用大写P把它命名为)
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";
我想它是这样的 \\ 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.
任何及所有帮助pciated AP $ P $
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");
这将使用或在您的用户帐户的App_Data文件创建一个文件夹,然后返回路径到该文件夹中的文件。请参阅 Environment.SpecialFolder
枚举其他位置可能的。
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.
这篇关于修改路径字符串,以提高耐用性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!