根据ListBox中SelectedItem的值删除文件



如何根据ListBox中的值在C#中删除文件。这是我的代码,不起作用:

File.Delete( folderBrowserDialog1.SelectedPath+ "" +listBox1.SelectedItem.ToString());

我假设您得到了一个null异常。您不能从ListBox中删除一个项,然后期望能够将其强制转换为字符串<--这在你编辑之前是相关的

另外,您正在用反斜杠""转义结束引号。您应该将其写成@"""\"String.Format("{0}{1}", path, fileName)Path.Combine(path, fileName)

I、 就我个人而言,我更喜欢后面的,因为我可以避免插入斜线,让它看起来更干净。

除此之外,最好在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,它将自行刷新。

最新更新