Relative Paths in Winforms

霸气de小男生 提交于 2019-11-28 10:10:21

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.

jjxtra

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);

// [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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!