Reputation: 79
I'm writing a program to delete a file or folder from my PC, but it seems that I can't get all the permissions to delete it.
Is there anyway to remove all the permissions from a file/folder, to make it possible to be deleted?
My code is:
//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;
}
I just want to get users permissions and be able to delete files with that permission.
Upvotes: 1
Views: 4749
Reputation: 2509
You cannot acquire the permissions from within the process. you need to run your program with administrative rights.
If you want to make your program available to run without admin rights, but only some parts of it need admin rights, you can separate your software in two different processes. (either two applications, or one main program application and another service running in the background to perform restricted tasks, each with their own set of pros & cons)
An extensive article on the topic of making your application UAC aware can be found here.
Upvotes: 2
Reputation: 441
In your app.manifest you need to set that your app require admin permission.
Change your requestedExcecutionLevel to this:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
Upvotes: 2