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

时间:2013-03-29 03:20:55

标签: c# relative-path

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

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

但这些没有运气...... 我已经在程序运行时将图像复制到输出目录,但它没有拾取这些图像。

4 个答案:

答案 0 :(得分:9)

如果您在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)

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

答案 1 :(得分:1)

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

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

有关GetExecutingAssembly的更多信息:MSDN Page

答案 2 :(得分:0)

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

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

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

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

答案 3 :(得分:-2)

如果您想使用应用程序在文件夹中显示图像,请使用数组并将所有图片放入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 u r using windows form application it must be a PictureBox i think.

    label1.Content = str;

}