C# SoundPlayer class 未在指定路径找到文件

C# SoundPlayer class isn't finding the file at the specified path

我正在使用 System.IO 命名空间的 Path.GetFullPath,它正确地提取了我存储在程序中的声音文件的绝对文件路径。它在 MessageBox 中显示它并且文件路径绝对正确。但是,当我使用 SoundPlayer 调用完全相同的文件路径时,它表示该位置不存在声音文件。我看不出我的代码有什么问题。

error message

absolute filepath

where the file is stored in the solution explorer

Path.GetFullPath returns 基于您的部分路径字符串和您的 当前目录

的完整路径

当前目录,如果您从例如windows 资源管理器,例如bin/Debug 您正在从中双击它。

如果您从 Visual Studio 调试器启动它,当前路径将是解决方案或项目目录(不记得了),无论如何默认。

所以这种获取文件路径的方案不起作用,如果你想同时做:有时从 Visual Studio 开始,有时直接(例如,如果你将二进制文件复制给其他人来尝试我们的你很酷的程序)。 尝试以下操作:

  • 在您的解决方案目录中,例如"data" 文件夹 除了 bin 文件夹和您的源文件等 - 假设您使用名为 "bin" 的文件夹的默认布局,其中二进制文件的 Debug 和 Release 文件夹是
  • 使用可靠的方法获取可执行文件的绝对路径
  • 利用您对目录结构的了解 "pedal back" 从可执行文件夹到 "data" 文件夹,您的音频文件可以在其中(直接或可能在 "audio" 子文件夹?)

可能看起来像这样:

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