wpf 创建位图时的相对路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28161900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Relative Path when creating Bitmap
提问by
I am trying to create a Bitmapusing:
我正在尝试创建一个Bitmap使用:
bitmap = new Bitmap(@"Movies\View\Images\missing_person.bmp");
However, I am receiving a System.ArgumentExceptionerror.
但是,我收到一个System.ArgumentException错误。
The file I'm calling the above code from is located in:
我正在调用上述代码的文件位于:
MyProj\DisplaySideBarCommand.cs
The images are in:
图片在:
MyProj\Movies\View\Images\missing_person.bmp
I also tried using:
我也尝试使用:
bitmap = new Bitmap(@"..\Movies\View\Images\missing_person.bmp");
but received the same error.
但收到同样的错误。
采纳答案by John Koerner
It is going to look for the files relative to the executing assembly. When you build your project it is probably output to a directory like bin\debugor bin\release. You could build your relative path to backtrack from there, or you could copy the files to the output directory.
它将查找与执行程序集相关的文件。当你构建你的项目时,它可能会输出到一个目录,比如bin\debug或bin\release。您可以构建相对路径以从那里回溯,或者您可以将文件复制到输出目录。
If you set the build action to Contenton the files, they will be copied to the output directory (including sub folders) on build and then you should be able to build the correct relative path from there.
如果您将构建操作设置为Content对文件,它们将在构建时复制到输出目录(包括子文件夹),然后您应该能够从那里构建正确的相对路径。
回答by Bauss
This is because the images are located in your project folder, not your output folder.
这是因为图像位于您的项目文件夹中,而不是您的输出文件夹中。
string projectFolder = "..\..\"; // Goes back to the project folder
Once you got the projec path simply use it like this:
获得项目路径后,只需像这样使用它:
bitmap = new Bitmap(projectFolder + @"Movies\View\Images\missing_person.bmp");
I would suggest you to move your files to the output folder rather than storing them in your project. Since normally you only distribute the output folder and not your whole project (Unless it's open source of course.)
我建议您将文件移动到输出文件夹,而不是将它们存储在您的项目中。因为通常你只分发输出文件夹而不是整个项目(当然除非它是开源的。)
回答by Viktors Garkavijs
If you are using the default settings, the debug binaries would be in ProjectDirectory\bin\Debug\- therefore, you might want to try @"..\..\Movies\View\Images\missing_person.bmp"
如果您使用默认设置,调试二进制文件将在ProjectDirectory\bin\Debug\- 因此,您可能想尝试@"..\..\Movies\View\Images\missing_person.bmp"

