Skip to main content
 首页 » 编程设计

c#之如何获得删除文件/文件夹的管理员权限

2024年02月05日11zhujiabin

我正在编写一个程序来从我的 PC 中删除文件或文件夹,但我似乎无法获得删除它的所有权限。

有什么方法可以删除文件/文件夹的所有权限,使其有可能被删除?

我的代码是:

//for each file in my filepath 
foreach (string ficheiro in caminhoFicheiros) 
{ 
    string deletar = "Deleting: "; 
    meuProgresso.Visible = true; 
    meuProgresso.Increment(1); 
    listBox.Items.Add(deletar + ficheiro.Substring(tamanho, ficheiro.Length - tamanho)); 
    //tamanho do ficheiro 
 
    long length = new System.IO.FileInfo(ficheiro).Length; 
    //lbMostrarItems.SelectedIndex = lbMostrarItems.Items.Count - 1; 
 
    // instead of doing a try catch, i want to be able to delete the file  
    // just by getting users permission. 
    try 
    { 
        File.Delete(ficheiro); 
        listBox.Items.Add("Deleted with sucess!"); 
    } 
    catch (IOException) 
    { 
        Thread.Sleep(0); 
    } 
    // i can´t delete the folder because i don´t have permissions. 
    catch (UnauthorizedAccessException) 
    { 
        File.Delete(ficheiro); 
    } 
 
    somarTamanho += length; 
} 

我只想获得用户权限并能够删除具有该权限的文件。

请您参考如下方法:

在您的 app.manifest 中,您需要设置您的应用需要管理员权限。

将您的 requestedExcecutionLevel 更改为此:

 <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />