App.config相对路径

问题描述 投票:6回答:5

我有文件夹“图标”。 我需要访问相同才能向imageList添加图标。 我正在使用具有相对路径的app.config文件。

<add key="doc" value="..\Icons\_Microsoft Office Excel 97-2003 Worksheet.ico" />

我正在使用下面的代码将其添加到imgList ,但它会抛出System.IO.FileNotFoundException

smallImageList.Images.Add(Image.FromFile(ConfigurationSettings.AppSettings["doc"]));

这有什么问题?

c# app-config
5个回答
7
投票

尝试添加当前运行路径:

smallImageList.Images.Add(Image.FromFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigurationSettings.AppSettings["doc"])));

2
投票

您可能需要将其与System.AppDomain.CurrentDomain.BaseDirectory连接。

我猜想FromFile是相对于当前工作目录很容易改变的。 另一件需要考虑的事情是将图像嵌入到程序集中


2
投票

转到属性,找到“复制到输出目录”属性,然后选择“始终复制”。 那应该没问题。 希望它会有所帮助。


0
投票

尝试使用蒂尔达...

value="~\Icons_Microsoft Office Excel 97-2003 Worksheet.ico"

哪个应该从应用程序根目录开始。


0
投票

在程序执行期间,您的工作文件夹已被修改,您必须找到自己的路径。

尝试这个:

using System.Reflection;
string CurrDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

smallImageList.Images.Add(Image.FromFile(Path.Combine(CurrDirectory,ConfigurationSettings.AppSettings["doc"])));
© www.soinside.com 2019 - 2024. All rights reserved.