I am trying to get the path of an image file which I added in solution explorer in Visual Studio, but I couldn't get the relative path of that image. H is the file structure of my project:
/BulutDepoProject /FolderIcon Folder.ico Main.cs
I can get the image like this :
"C:\\Users\\Tolga\\Desktop\\BulutDepo\\BulutDepoProject\\FolderIcon\\Folder.ico"
But I should be able to get it with something like :
"~\\FolderIcon\\Folder.ico"
I guess I don't know the exact syntax of it so I cant fetch the image. :(
I also met the same problem and I was able to get it through. So let me explain the steps I applied. I shall explain it according to your scenario.
According to my method we need to use 'Path' class and 'Assembly' class in order to get the relative path.
So first Import System.IO and System.Reflection in using statements.
Then type the below given code line.
Actually above given line stores the path of the output directory of your project.(Here 'output' directory refers to the Debug folder of your project).
Now copy your FolderIcon directory in to the Debug folder. Then type the below given Line.
Now this 'iconPath ' variable contains the entire path of your Folder.ico. All you have to do is store it in a string variable. Use the line of code below for that.
Now you can use this icon_path string variable as your relative path to the icon.
Thanks.
I'm a little late, and I'm not sure if this is what you're looking for, but I thought I'd add it just in case someone else finds it useful.
Suppose this is your file structure:
You need to write your path relative to the
Main.exe
file. So, you want to accessFolder.ico
, in yourMain.cs
you can use:That seemed to work for me!
I think using this will be the easiest
or this code will work on any machine that if your folder is in your root project if you want to change it... just change this section @"..\"
Omit the "~\":
~\
doesn't mean anything in terms of the file system. The only place I've seen that correctly used is in a web app, where ASP.NET replaces the tilde with the absolute path to the root of the application.You can typically assume the paths are relative to the folder where the EXE is located. Also, make sure that the image is specified as "content" and "copy if newer"/"copy always" in the properties tab in Visual Studio.
When it is the case that you want to use any kind of external file, there is certainly a way to put them in a folder within your project, but not as valid as getting them from resources. In a regular Visual Studio project, you should have a
Resources.resx
file under theProperties
section, if not, you can easily add your ownResource.resx
file. And add any kind of file in it, you can reach the walkthrough for adding resource files to your project here.After having resource files in your project, calling them is easy as this:
Of course you should add the
using Properties
statement like this: