You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将字符串变量传入SoundPlayer?路径格式不支持报错如何解决?

问题原因
  • 核心错误是你调用了列表框控件本身的ToString()方法,而非列表框中选中项的内容。默认情况下listBox1.ToString()返回的是控件的类型描述文本(如"System.Windows.Forms.ListBox, Items.Count: 5"),而非你期望的选中文件路径,不符合系统路径格式要求。
  • 如果你调试时确实看到fileLocation的值为目标路径,大概率是字符串中包含了多余的前后空格、不可见字符、甚至额外的引号,这些内容都会被系统判定为非法路径格式。
修复方案
  1. 优先修改路径取值逻辑,从选中项提取路径,同时清除多余无效字符:
// 先判断是否存在选中项
if (listBox1.SelectedItem != null)
{
    // 从选中项获取路径,Trim()清除前后多余空格/不可见字符
    string fileLocation = listBox1.SelectedItem.ToString().Trim();
    // 增加文件存在性校验,提前拦截异常
    if (!File.Exists(fileLocation))
    {
        MessageBox.Show("指定音频文件不存在");
        return;
    }
    SoundPlayer splayer = new SoundPlayer(fileLocation);
    splayer.Play();
}
  1. 如果你是将FileInfo对象直接绑定为列表项,需要显式读取完整路径属性:
if (listBox1.SelectedItem is FileInfo selectedFile)
{
    string fileLocation = selectedFile.FullName;
    SoundPlayer splayer = new SoundPlayer(fileLocation);
    splayer.Play();
}

内容的提问来源于stack exchange,提问作者TuckRollworthy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 16:54:03