How to set relative path to Images directory insid

2020-07-19 05:37发布

问题:

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.

回答1:

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.



回答2:

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



回答3:

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.



回答4:

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;

}