我正在使用System.IO命名空间的Path.GetFullPath,它正在正确提取我存储在程序中的声音文件的绝对文件路径。它在MessageBox中显示它,并且文件路径绝对正确。但是,当我使用SoundPlayer调用完全相同的文件路径时,就是说该位置不存在声音文件。我的代码绝对没有错。
Path.GetFullPath返回基于您的部分路径字符串和当前目录
的完整路径当前目录,如果您从例如Windows资源管理器,例如bin / Debug,双击它。
如果从Visual Studio调试器启动,则默认情况下,当前路径将是解决方案或项目目录(不记得了)。
因此,如果您想同时执行以下两种操作,则无法使用这种获取文件路径的方案:有时是从Visual Studio开始的,有时是直接启动的(例如,如果将二进制文件复制到其他人尝试我们很酷的程序)。尝试以下操作:
可能看起来像这样:
using System.IO; // ... public static string GetExeDirSubPath(string subPath) { return new DirectoryInfo( Path.Combine( GetExeDirPath(), subPath ) ).FullName; // DI stripts dtuff like "..\..\" and moves to the actual path } public static string GetExeDirPath() { System.Reflection.Assembly a = System.Reflection.Assembly.GetEntryAssembly(); string baseDir = System.IO.Path.GetDirectoryName(a.Location); return baseDir; }
然后,使用上面列出的目录结构,您将获得音频文件的完整路径:
// first "..": go from Debug or Release folder of your exe to bin
// second "..": go from bin to the folder containing both: bin and data folders
var fullpath = GetExeDirSubPath( "../../data/audio/silly_sound.wav" );