我假设你得到一个空异常。您不能从 ListBox 中删除项目,然后期望能够将其转换为字符串。
此外,您正在使用反斜杠 "\" 转义右引号。您应该将其写为@"\"、"\\"、String.Format("{0}\{1}", path, fileName) 或Path.Combine(path, fileName)。
我个人更喜欢后者,因为我可以避免插入斜线并使其看起来更干净。
除此之外,最好在 IO 代码周围设置一个 try{}catch{} 块,以捕获尝试删除文件时可能发生的任何异常。如果您处于多用户环境中并且其他人移动该文件、打开它等,除非您的代码考虑到它,否则您将收到异常。
我还想检查所选项目是否为空。个人喜好。
if (listBox1.SelectedItem == null)
{
System.Diagnostics.Debug.WriteLine("Selection is null");
return;
}
try
{
File.Delete(Path.Combine(folderBrowserDialog1.SelectedPath,
listBox1.SelectedItem.ToString()));
}
catch (System.IO.IOException e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
}
如果要验证文件是否存在,可以使用:
if (File.Exists(Path.Combine(folderBrowserDialog1.SelectedPath,
listBox1.SelectedItem.ToString())))
{
// your code here
}
但如果您有类似上述的 try{}catch{} 块,则没有必要。
除了上述之外,我想补充一点,当您编写原始代码时,我看到了一些有趣的事情。您正在删除一个文件,从选择框中删除一个项目,然后刷新该选择框。我可以推荐使用ObservableCollection<T>() 吗?每当您通过添加或删除项目来更新此集合时,从该集合中获取其项目的任何内容都将收到更新通知。对于 ListBox,它会自行刷新。