0

Why wont the files in the test folder delete?? How can i get admin access??

namespace Delete
{
    using System;
    using System.Windows.Forms;
    using System.IO;

    public class Delete
    {
        public Delete()
        {
            if (Directory.Exists(@"C:\Program Files (x86)\test\"))
            {
                string[] filePaths = Directory.GetFiles(@"C:\Program Files (x86)\test\");
                foreach (string file in filePaths) { File.Delete(file); }
            }
        }
    }
}
jitsuin
  • 269
  • 1
  • 3
  • 7
  • 2
    Run it from an elevated command prompt. – vcsjones Apr 24 '12 at 18:33
  • well this will be injected into a program that runs from an exe, ill have to look into what your saying, the exe would have to be run as an admin then no? – jitsuin Apr 24 '12 at 18:37

3 Answers3

3

You need to rethink your strategy.

If you are adding/removing files programatically from within your application, they should be stored in a separate location (that won't need admin privs to elevate for writing/deleting, etc.):

  1. like the user's data directory/your company/your application, or
  2. the user's documents/your company/your application

The Program Files directory is for application specific files (DLL's, etc) that are installed with the program but don't change once installed/updated.

Here's an example of the User's Data directory by application:

public static DirectoryInfo ApplicationVersionDirectory()
{
    return new DirectoryInfo(System.Windows.Forms.Application.UserAppDataPath);
}
Chuck Savage
  • 11,775
  • 6
  • 49
  • 69
2

This is due to the UAC. So either run your executable as admin by right clicking -> "Run as Administrator" or if you want to do it programatically refer to other posts like Windows 7 and Vista UAC - Programmatically requesting elevation in C#

Community
  • 1
  • 1
banging
  • 2,540
  • 1
  • 22
  • 26
0

In order to delete files from "Program Files" folder you need to start application as an administrator. Otherwise you will not be able to get an access to %PROGRAMFILES%.

Here is the sample code to restart current app and run it as admin:

ProcessStartInfo proc = new ProcessStartInfo();
proc.UseShellExecute = true;
proc.FileName = Application.ExecutablePath;
proc.Verb = "runas";



try
            {

                Process.Start(proc);

            }

            catch

            {

                // The user refused the elevation.

                // Do nothing and return directly ...

                return;

            }

            Application.Exit();  // Quit itself
OrahSoft
  • 783
  • 1
  • 5
  • 7