简体   繁体   English

如何从C#中的特定目录加载图像?

[英]How can I load an image from a specific directory in C#?

I would like to load an image from a directory "../MyAppFolder/Logos". 我想从目录“ ../MyAppFolder/Logos”中加载图像。

My code: 我的代码:

 Bitmap bmp = new Bitmap(@"/Logos/bitmap.bmp");
 pictureBox1.Image = bmp;

This code doesn't work. 此代码无效。 When I use (@"/Bitmapx.bmp") it works, but when I want to load an image from a deeper directory I get an error message. 当我使用(@“ / Bitmapx.bmp”)时,它可以工作,但是当我想从更深的目录中加载图像时,会出现错误消息。

What am I doing wrong? 我究竟做错了什么?

The leading slash targets the current drive root. 前导斜线针对当前驱动器根目录。 Use the realative path... 使用现实的道路...

Bitmap bmp = new Bitmap(@"Logos/bitmap.bmp"); 

..Or one of the many Path. ..或众多Path. methods to resolve the full path that you want. 解决所需完整路径的方法。

and yes I know my example above targets the current working path... that would be why I added the above comment. 是的,我知道上面的示例针对的是当前工作路径……这就是为什么我添加以上注释的原因。 And for the pointless downvoter you might like to learn that current versions of Windows don't care which slash you use. 对于毫无意义的下士,您可能想了解一下,当前版本的Windows不在乎您使用哪个斜杠。

Try this: 尝试这个:

string myLogo = System.IO.Path.Combine(Application.StartupPath, @"Logos\bitmap.bmp");
Bitmap bmp = new Bitmap(myLogo);
pictureBox1.Image = bmp;

And make sure your Logos folder is in your application root folder. 并确保徽标文件夹位于应用程序的根文件夹中。

The first character of your path is / which makes this path relative to the root level of the drive on which the current working directory lives. 路径的第一个字符是/ ,它使该路径相对于当前工作目录所在的驱动器的根目录级别。 But you probably want a relative path so just remove the initial / . 但是您可能需要相对路径,因此只需删除首字母/

What's more, relative paths are relative to the working directory. 而且,相对路径是相对于工作目录的。 But the working directory is not necessarily the application directory. 但是工作目录不一定是应用程序目录。 For example, if you navigate in a file dialog that can change your working directory. 例如,如果您在可以更改工作目录的文件对话框中导航。

If I were you I would probably pre-pend the path with the app directory and make it a fully-specified absolute path, exactly as HABJAN suggests. 如果您是我,我可能会在路径前加上app目录,并将其设置为完全指定的绝对路径,正如HABJAN所建议的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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