Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Check for Windows 7 Protected Folders

4.38/5 (8 votes)
20 Oct 2011CPOL 37.8K  
Check for Windows 7 Protected Folders
.NET 2.0 File.Copy() (build using VS2005) function does not throw any exception if you want to copy a file in Windows 7 protected folder like "C:\", "C:\Program Files", etc. and it does not perform the copy operation too. Actually it performs the desired copy operation in virtual file store, i.e., %localappdata%\VirtualStore. This works as expected if you run your application as administrator. Below is a tip to check if the folder is protected or not, i.e., you can use File.Copy() method as a target folder in File.Copy() .

C#
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.AccessControl;
using System.Security.Principal;

namespace FolderAccess
{
   class Program
   {
      private static bool IsProtected(string folder)
      {
         DirectorySecurity ds = new DirectorySecurity(folder, AccessControlSections.Access);
         if (ds.AreAccessRulesProtected)
         {

            WindowsIdentity wi = WindowsIdentity.GetCurrent();
            WindowsPrincipal wp = new WindowsPrincipal(wi);

            return !wp.IsInRole(WindowsBuiltInRole.Administrator); // Not running as admin
         }

         return false;
      }

      static void Main(string[] args)
      {
         if (IsProtected("C:\\"))
         {
            Console.WriteLine("Protected folder");
         }
         else
         {
            Console.WriteLine("Not a protected folder");
         }
         Console.ReadKey();
      }
   }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)