2009-08-26 158 views
6

我有文件夹“图标”。 我需要访问它才能将图标添加到imageList。 我使用的app.config文件中有一个相对路径。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"])); 

这里有什么问题吗?

回答

7

尝试将当前运行路径:

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

谢谢你,那个工作..甚至 Path.GetFullPath(ConfigurationSettings.AppSettings [“doc”]);这工作..我想知道是我在做什么错误 smallImageList.Images.Add(Image.FromFile(ConfigurationSettings.AppSettings [“doc”])); – Anees 2009-08-26 12:46:22

+0

smallImageList.Images.Add(Image.FromFile(Path.GetFullPath(ConfigurationSettings.AppSettings [“doc”]))); – Anees 2009-08-26 13:06:24

+0

这应该被标记为答案。问题似乎是'Image.FromFile'需要一个绝对路径,而不是相对路径。 – Oliver 2013-03-27 13:31:54

0

尝试使用蒂尔达...

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

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

2

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

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

+0

哇,我不知道那个。多简单多了,我的GetExecutingAssembly()解决方案... – Vinzz 2009-08-26 12:48:24

0

您的工作文件夹在程序执行过程中以某种方式被修改,您必须找到自己的路径。

试试这个:

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

smallImageList.Images.Add(Image.FromFile(Path.Combine(CurrDirectory,ConfigurationSettings.AppSettings["doc"]))); 
+0

喜Vinzz, 它检索路径 C:\ Documents和Settings \ ADMIN \我的文档\ Visual Studio 2008的\项目\ IconsLoadinginTreeview_Files_Demo \ IconsLoadinginTreeview_Files_Demo \ BIN \调试\。 \图标\ _Microsoft办公室Excel 97-2003 Worksheet.ico “..”在filPath再次抛出错误 – Anees 2009-08-26 13:01:16

+0

当然,您的里程可能会有所不同。如有必要,在那里或那里添加一个额外的'..'。我不知道你的图标真的在哪里; o)顺便说一句,似乎你已经找到了解决方案,不是吗? – Vinzz 2009-08-26 13:21:11

2

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