Reputation: 13
In the solution I have a console app (MyApp) which executes a method from another project (MyProject). In MyProject I have a folder with images. How can refer to an image from the folder with e.g. Image.FromFile()?
Methods like Directory.GetCurrentDirectory() will return the path of the MyApp not MyProject Am I missing something obvious?
Upvotes: 1
Views: 12351
Reputation: 12328
If the files are included in the project, another option is to go to the Properties tab and mark the Build Action as "Content" and the Copy to Output Directory as either "Copy always" or "Copy if newer." This way the files will appear in a path relative to your assembly.
Upvotes: 1
Reputation: 478
You can mark your image files as embedded resource. Right click on your image files > Properties, set Build Action to Embedded Resource.
At MyProject
, create public method which return image, in this case the path
signature should be manifest resource name..
public Image FindImageByPath(string path) // eg: MyProject.ImageFolder.MyImage.png
{
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(path))
return Image.FromStream(stream);
}
Another way is to store your images into resource file (.resx).
Upvotes: 3
Reputation: 77
You could simply reference that file path directly, i.e. if I had pictures outside of my project folder I could use
string fileName = "picture1";
string fileExtension = ".png";
var image1 = Image.FromFile($@"C:\Users\Me\Desktop\Pictures\{fileName}{fileExtension}")
Alternatively, "..\" moves up a folder in the current directory and "\\" refers to a global directory
Remember to use the string literal '@' unless you want to escape every '\' in the file path. Use '$' for string interpolation If you use both '$' AND '@', you MUST use them in the order '$@'
Upvotes: 1