如何将字符串变量传入SoundPlayer?路径格式不支持报错如何解决?
问题原因
- 核心错误是你调用了列表框控件本身的
ToString()方法,而非列表框中选中项的内容。默认情况下listBox1.ToString()返回的是控件的类型描述文本(如"System.Windows.Forms.ListBox, Items.Count: 5"),而非你期望的选中文件路径,不符合系统路径格式要求。 - 如果你调试时确实看到
fileLocation的值为目标路径,大概率是字符串中包含了多余的前后空格、不可见字符、甚至额外的引号,这些内容都会被系统判定为非法路径格式。
修复方案
- 优先修改路径取值逻辑,从选中项提取路径,同时清除多余无效字符:
// 先判断是否存在选中项 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(); }
- 如果你是将
FileInfo对象直接绑定为列表项,需要显式读取完整路径属性:
if (listBox1.SelectedItem is FileInfo selectedFile) { string fileLocation = selectedFile.FullName; SoundPlayer splayer = new SoundPlayer(fileLocation); splayer.Play(); }
内容的提问来源于stack exchange,提问作者TuckRollworthy
相关产品推荐
相关产品推荐

