简体   繁体   中英

How to set relative path to Images directory inside C# project?

I am working on C# project i need to get the images from Images directory using relative path. I have tried

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

But no luck with these... I have made the images to be copied to output directory when the program is running but it doesn't pickup those images.

If you are using LinkedResource() in C# it is most likely not to pickup your relative URI or the file location.

You can use some extra piece of code

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)

Now it will pickup your relative path, convert this to absolute path in memory and it will help you get the images.

I would make sure that the Images directory is in the output folder. I usually use Assembly.GetExecutingAssembly().Location to get the location of my dll.

However, for images, I usually use the Resources page/collection in the project's Properties page. Here is more information about it. Putting the image in the project's Resource would automatically give you an easy way to access it.

For more information about GetExecutingAssembly: MSDN Page

First, add those image file to your project (create an Image folder is a good idea)

Second, select the image in your solution manager, and view the property window.

And then, change the "copy to output folder" to "always" or "copy when update".

PS. My IDE is Trad. Chinese so I can not ensure the correct keywords in your language.

if u want to display images in your folder using your application use an array and put all pictures in ur folder into array. then you can go forward and backward.

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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM