C#SoundPlayer类在指定路径下找不到文件

问题描述 投票:0回答:1

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

error message

absolute filepath

where the file is stored in the solution explorer

c# wpf filepath soundplayer
1个回答
1
投票

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

的完整路径

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

如果从Visual Studio调试器启动,则默认情况下,当前路径将是解决方案或项目目录(不记得了)。

因此,如果您想同时执行以下两种操作,则无法使用这种获取文件路径的方案:有时是从Visual Studio开始的,有时是直接启动的(例如,如果将二进制文件复制到其他人尝试我们很酷的程序)。尝试以下操作:

  • 在您的解决方案目录中,例如“ data”文件夹beides bin文件夹和您的源文件等-假设您使用名为“ bin”的文件夹的默认布局,其中二进制文件的Debug和Release文件夹为]]
  • 使用可靠的方法获取可执行文件的绝对路径
  • 使用您对目录结构的了解,从可执行文件文件夹“回踩”到“数据”文件夹,您的音频文件可以位于其中(直接位于音频文件夹中,也可以位于“音频”子文件夹中?)
  • 可能看起来像这样:

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" );
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.