如何在C#项目中设置Images目录的相对路径?

我正在研究C#项目我需要使用相对路径从Images目录中获取图像。 我试过了

var path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + @"\Images\logo.png"; var logoImage = new LinkedResource(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)+@"\Images\logo.png") 

但是没有运气这些…我已经让图像在程序运行时被复制到输出目录但它没有拾取那些图像。

如果您在C#中使用LinkedResource(),则很可能不会获取相对URI或文件位置。

您可以使用一些额外的代码

 var outPutDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase); var logoimage = Path.Combine(outPutDirectory, "Images\\logo.png"); string relLogo = new Uri(logoimage).LocalPath; var logoImage = new LinkedResource(relLogo) 

现在它将拾取您的相对路径,将其转换为内存中的绝对路径,它将帮助您获取图像。

我会确保Images目录位于输出文件夹中。 我通常使用Assembly.GetExecutingAssembly().Location来获取我的dll的位置。

但是,对于图像,我通常使用项目的“属性”页面中的“资源”页面/集合。 以下是有关它的更多信息。 将图像放在项目的资源中会自动为您提供一种访问它的简便方法。

有关GetExecutingAssembly的更多信息: MSDN页面

首先,将这些图像文件添加到您的项目中(创建一个Image文件夹是一个好主意)

其次,在解决方案管理器中选择图像,然后查看属性窗口。

然后,将“复制到输出文件夹”更改为“始终”或“更新时复制”。

PS。 我的IDE是Trad。 中文,所以我无法确保您的语言中的正确关键字。

如果您想使用应用程序在文件夹中显示图像,请使用数组并将所有图片放入ur文件夹中。 然后你可以前进和后退。

 string[] _PicList = null; int current = 0; _PicList = System.IO.Directory.GetFiles("C:\\Documents and Settings\\Hasanka\\ Desktop\\deaktop21052012\\UPEKA","*.jpg"); // "*.jpg" will select all //pictures in your folder String str= _PicList[current]; DisplayPicture(str); private void DisplayPicture(string str) { //throw new NotImplementedException(); BitmapImage bi = new BitmapImage(new Uri(str)); imagePicutre.Source = bi; // im using Image in WPF //if ur using windows form application it must be a PictureBox i think. label1.Content = str; }