Relative paths in Winforms

Relative paths in C # work for me. In one case, Im is processing a set of Texture2d objects for my application, taking the file name and using it to find files and load textures into image objects. Then I load the image from the relative path stored in the class file and use the relative path, which should be relative to Content / gfx. But if I do not load these textures, these relative paths will fail. How can I explain that my rel path will not fail? In web work, all rel paths refer to the folder in which the file we are working from is located, can I configure it this way and make all rel paths to the root folder where my application is located?

+7
c # winforms relative-path
source share
3 answers

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 EXE startup:

string exeFile = (new System.Uri(Assembly.GetEntryAssembly().CodeBase)).AbsolutePath; 

Once you have this, you can get its directory:

 string exeDir = Path.GetDirectoryName(exeFile); 

and turn your relative path to the absolute path:

 string fullPath = Path.Combine(exeDir, "..\\..\\Images\\Texture.dds"); 

This will be much more reliable than using relative paths.

+18
source share

If you expect the resource to be in the same directory as the executable or in a subdirectory of this directory, it is best to use

 string fullPath = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), subPath); 

or if you are concerned that the working directory might be wrong, you can do this:

 string fullPath = System.IO.Path.Combine(System.Reflection.Assembly.GetEntryAssembly().Location, subPath); 
+1
source share

// [namespace] is the namespace // you must copy the file .-- to the 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(); 
0
source share

All Articles