C# 如何在程序的 app.config 文件中存储文件路径?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13826740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How may I store a file path in my program's app.config file?
提问by veronika.np
I have written a C# program for saving and reading PDF files. The program saves the output files to the local computer's bin folder. I want my program to access files from a different computer.
我编写了一个用于保存和阅读 PDF 文件的 C# 程序。该程序将输出文件保存到本地计算机的 bin 文件夹中。我希望我的程序可以从另一台计算机访问文件。
I have heard about keeping a file path stored in the app.configof my program, but I don't know how to do this.
我听说过将文件路径存储在app.config我的程序中,但我不知道如何做到这一点。
How may I store a file path in my program's app.config file?
如何在程序的 app.config 文件中存储文件路径?
回答by Scott Chapman
You can store the file path in an app.config file by using this format in the app config:
您可以在应用配置中使用以下格式将文件路径存储在 app.config 文件中:
<configuration>
<appSettings>
<add key="Path" value="\ComputerName\ShareName"/>
</appSettings>
</configuration>
You can then read the app settings stored there using the ConfigurationManager class. You'll have to add a reference to System.Configuration in your project, and reference it in the code.
然后,您可以使用 ConfigurationManager 类读取存储在那里的应用程序设置。您必须在项目中添加对 System.Configuration 的引用,并在代码中引用它。
After that, your path can be read by accessing ConfigurationManager.AppSettings["Path"]- it will be a string.
之后,您的路径可以通过访问读取ConfigurationManager.AppSettings["Path"]- 它将是一个string.
回答by CDGreeneyes
I'm a complete noob but I recently had the same issue so here is what I came up with.
我是一个完整的菜鸟,但我最近遇到了同样的问题,所以这就是我想出的。
The solution is three seperate steps:
解决方案是三个单独的步骤:
As stated in the answer above, you add a key value to App.config that points to your path:
<configuration> <appSettings> <add key="Path" value="C:\text.txt"/> </appSettings> </configuration>You need the using statement: using System.Configuration;
如上面的答案所述,您向 App.config 添加了一个指向您的路径的键值:
<configuration> <appSettings> <add key="Path" value="C:\text.txt"/> </appSettings> </configuration>您需要使用语句: using System.Configuration;
Besides these two, you also need a reference to the assembly.
除了这两个之外,您还需要对程序集的引用。
- Right click on References in Solution Explorer.
- Click Add Reference.
- Click on Assemblies and type "Configuration" in the search box.
- Put a check mark on System.Configuration.
- 右键单击解决方案资源管理器中的引用。
- 单击添加引用。
- 单击程序集并在搜索框中键入“配置”。
- 在 System.Configuration 上打勾。
The message "ConfigurationManaager does not exist in the current context" should be gone and you have your file path!
“ConfigurationManager 在当前上下文中不存在”消息应该消失了,你有你的文件路径!

