Winforms中的相对路径

C#中的相对路径对我来说很复杂。 在一种情况下,我将一组Texture2d对象处理到我的应用程序,它获取文件名并使用它来定位文件并将纹理加载到Image对象中。 然后,我从存储在类文件中的相对路径加载图像,并使用需要相对于Content / gfx的相对路径。 但如果我不加载这些纹理,这些相对路径将失败。 我怎么能认为我的相对路径不会失败? 在Web工作中,所有rel路径都是相对于我们正在处理的文件所在的文件夹,我可以这样设置它并将所有rel路径设置为我的应用程序所在的根文件夹吗?

我建议首先不要使用相对路径。

使用Path.Combine将相对路径转换为绝对路径。 例如,您可以使用它来获取启动EXE的完整路径:

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

一旦你有了,你可以得到它的目录:

 string exeDir = Path.GetDirectoryName(exeFile); 

并将您的相对路径转换为绝对路径:

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

这比尝试使用相对路径更可靠。

如果您希望资源与可执行文件位于同一目录中或该目录的子目录中,则最好始终使用

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

或者如果您担心工作目录可能有误,可以这样做:

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

// [名称空间]是名称空间//您应该将文件.–复制到Depug文件中

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