用c#删除文件

Deleting Files with c#

我正在制作一个程序来删除我电脑上的一些文件。但是当我尝试这样做时,我收到了一些这样的错误消息:

If you are attempting to access a file, make sure it is not ReadOnly.

Make Sure you have sufficient privileges to access this resource.

Get general Help for this exception.

    foreach (string subFich in SubFicheiros)
    {
        listBox.Items.Add("- Deleting File: " + subFich.Substring(Pasta.Length + 1, subFich.Length - Pasta.Length - 1));
        ficheirosEncontrador++;
    }
    try
    {
        Directory.Delete(Pasta, true);
    }
    catch (IOException)
    {
        Thread.Sleep(0);
    //The Message Error appears here on this code right below:
            Directory.Delete(Pasta, true);

    }
    catch (UnauthorizedAccessException)
    {
        Directory.Delete(Pasta, true);
    }
}

我想得到一些帮助。 我怎么问用户,让我获得删除它的权限。

听起来你的文件是只读的,或者你无权根据你的用户登录删除你想要的文件。

好吧.. 你的代码在做什么:你正在删除目录,如果它给出任何异常,那么你将再次尝试执行出现异常的相同步骤。

首先错误是因为文件被设置为只读或者因为您没有足够的权限删除目录(或者可能某些进程正在使用您试图删除的文件)

 foreach (string subFich in SubFicheiros)
{
    listBox.Items.Add("- Deleting File: " + subFich.Substring(Pasta.Length + 1, subFich.Length - Pasta.Length - 1));
    ficheirosEncontrador++;
}
try
{
var di = new DirectoryInfo(Pasta);
di.Attributes &= ~FileAttributes.ReadOnly;
 Directory.Delete(Pasta, true);
}
catch (Exception EE)
{

 MessageBox.Show("Error: "+ EE.toString());
}

如果此代码仍然无效,请检查您是否具有删除该文件夹的管理员权限