Relative paths in C# are acting screwy for me. In one case Im handling a set of Texture2d objects to my app, its taking the filename and using this to locate the files and load the textures into Image objects. I then load an image from a relative path stored in the class file and use a relative path that needs to be relative to Content/gfx. But if i dont load these textures these relative paths will fail. How can I garuantee that my rel path wont fail? In web work all rel paths are relative to the folder the file we're working from is in, can I set it up this way and make all rel paths to root folder where my app is located?
Asked
Active
Viewed 2.3k times
11
-
Is this in debug or in deployed mode? – chris.w.mclean Jun 19 '09 at 19:24
3 Answers
25
I recommend not using relative paths in the first place.
Use Path.Combine to turn your relative paths into absolute paths. For example, you can use this to get the full path to your startup EXE:
string exeFile = (new System.Uri(Assembly.GetEntryAssembly().CodeBase)).AbsolutePath;
Once you have that, you can get it's directory:
string exeDir = Path.GetDirectoryName(exeFile);
and turn your relative path to an absolute path:
string fullPath = Path.Combine(exeDir, "..\\..\\Images\\Texture.dds");
This will be much more reliable than trying to use relative paths.

Reed Copsey
- 554,122
- 78
- 1,158
- 1,373
-
Thx alot for the two first lines, just was I was looking for. I would use '@' in the third line to avoid double backslashs though. – radbyx Apr 18 '11 at 12:31
-
If my directory has a space in it, it can't find the path, but if it does not, it works fine. – Xaisoft Dec 07 '12 at 19:28
-
3
If you are expecting a resource to be in the same directory as the executable file or in a sub directory of that directory, it's best to always use
string fullPath = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), subPath);
or if you are worried that the working directory might be wrong you can do this:
string fullPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), subPath);
0
// [name space] is name space //you should copy your file.-- into Depug file
string path = (Assembly.GetEntryAssembly().Location + "");
path = path.Replace("name space", "filename.--");
// [WindowsFormsApplication4] is name space
//you should copy your "mysound.wav" into Depug file
//example::
string path_sound = (Assembly.GetEntryAssembly().Location + "");
path_sound = path_sound.Replace("WindowsFormsApplication4.exe", "mysound.wav");
SoundPlayer player1 = new SoundPlayer(path_sound);
player1.Play();