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);
            }
        }
Beispiel #2
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);
        }
        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);
            }
        }
        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"));
            }
        }
Beispiel #5
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;
            }
        }
Beispiel #6
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
        }
 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);
 }
        /// <summary>
        /// 向指定的文件或目录追加访问权限。
        /// </summary>
        /// <param name="path">文件或目录路径。</param>
        /// <param name="identity">Windows 用户或组名称。</param>
        /// <param name="fileSystemRights">访问权限。</param>
        /// <param name="accessControlType">指定允许还是拒绝该操作。</param>
        public static void AppendPermission(string path, string identity, System.Security.AccessControl.FileSystemRights fileSystemRights, System.Security.AccessControl.AccessControlType accessControlType)
        {
            System.Security.AccessControl.FileSystemAccessRule ar1 = new System.Security.AccessControl.FileSystemAccessRule(identity, fileSystemRights, accessControlType);

            if (System.IO.Directory.Exists(path))
            {
                System.Security.AccessControl.FileSystemAccessRule ar2 = new System.Security.AccessControl.FileSystemAccessRule(identity, fileSystemRights, System.Security.AccessControl.InheritanceFlags.ContainerInherit | System.Security.AccessControl.InheritanceFlags.ObjectInherit, System.Security.AccessControl.PropagationFlags.InheritOnly, accessControlType);

                System.Security.AccessControl.DirectorySecurity ds = System.IO.Directory.GetAccessControl(path);
                ds.AddAccessRule(ar1);
                ds.AddAccessRule(ar2);
                System.IO.Directory.SetAccessControl(path, ds);
            }
            else if (System.IO.File.Exists(path))
            {
                System.Security.AccessControl.FileSecurity ds = System.IO.File.GetAccessControl(path);
                ds.AddAccessRule(ar1);
                System.IO.File.SetAccessControl(path, ds);
            }
        }
Beispiel #9
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);
 }
Beispiel #10
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);
                }
            }
        }
Beispiel #11
0
        private void Directory_CreateDirectory_WithDirectorySecurity(bool isNetwork)
        {
            UnitTestConstants.PrintUnitTestHeader(isNetwork);
            Console.WriteLine();


            var tempPath = System.IO.Path.GetTempPath();

            if (isNetwork)
            {
                tempPath = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(tempPath);
            }


            using (var rootDir = new TemporaryDirectory(tempPath, MethodBase.GetCurrentMethod().Name))
            {
                var folder = rootDir.RandomDirectoryFullPath;
                Console.WriteLine("\tInput Directory Path: [{0}]", folder);
                Console.WriteLine();


                var pathExpected = rootDir.RandomDirectoryFullPath;
                var pathActual   = rootDir.RandomDirectoryFullPath;

                var sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
                var expectedDirectorySecurity = new System.Security.AccessControl.DirectorySecurity();
                expectedDirectorySecurity.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(sid, System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
                expectedDirectorySecurity.AddAuditRule(new System.Security.AccessControl.FileSystemAuditRule(sid, System.Security.AccessControl.FileSystemRights.Read, System.Security.AccessControl.AuditFlags.Success));


                using (new Alphaleonis.Win32.Security.PrivilegeEnabler(Alphaleonis.Win32.Security.Privilege.Security))
                {
                    var s1 = System.IO.Directory.CreateDirectory(pathExpected, expectedDirectorySecurity);
                    var s2 = Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(pathActual, expectedDirectorySecurity);


                    var expected = s1.GetAccessControl().GetSecurityDescriptorSddlForm(System.Security.AccessControl.AccessControlSections.All);
                    var actual   = s2.GetAccessControl().GetSecurityDescriptorSddlForm(System.Security.AccessControl.AccessControlSections.All);


                    Console.WriteLine("\tSystem.IO: {0}", expected);
                    Console.WriteLine("\tAlphaFS  : {0}", actual);


                    Assert.AreEqual(expected, actual);
                }
            }

            Console.WriteLine();
        }
        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();
        }
Beispiel #13
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();
        }
Beispiel #14
0
        public static SlideInfo LoadSlideInfo()
        {
            if (!File.Exists(SlideShowPath + "\\" + "SlideInfo.js"))
            {
                if (!Directory.Exists(SlideShowPath))
                {
                    var dirSecurity = new System.Security.AccessControl.DirectorySecurity(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), System.Security.AccessControl.AccessControlSections.Access);
                    dirSecurity.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule("Authenticated Users", System.Security.AccessControl.FileSystemRights.Modify, System.Security.AccessControl.AccessControlType.Allow));

                    Directory.CreateDirectory(SlideShowPath, dirSecurity);
                }
                return(new SlideInfo());
            }

            using (StreamReader file = File.OpenText(SlideShowPath + "\\" + "SlideInfo.js"))
            {
                JsonSerializer serializer = new JsonSerializer();
                return((SlideInfo)serializer.Deserialize(file, typeof(SlideInfo)));
            }
        }
Beispiel #15
0
 public static DirectoryInfo GetOrCreateSessionTempFolder(string SessionID)
 {
     try
     {
         string tmpPath = System.IO.Path.Combine(GetOrCreateApplicationTempFolder().FullName, SessionID);
         System.IO.DirectoryInfo tmpPathDirInfo = new System.IO.DirectoryInfo(tmpPath);
         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);
     }
     catch
     {
     }
     return(new DirectoryInfo(System.IO.Path.GetTempPath()));
 }
        private void Directory_CreateDirectory_WithDirectorySecurity(bool isNetwork)
        {
            using (var tempRoot = new TemporaryDirectory(isNetwork))
            {
                var folder = tempRoot.RandomDirectoryFullPath;

                Console.WriteLine("Input Directory Path: [{0}]\n", folder);


                var pathExpected = tempRoot.RandomDirectoryFullPath;
                var pathActual   = tempRoot.RandomDirectoryFullPath;


                var sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
                var expectedDirectorySecurity = new System.Security.AccessControl.DirectorySecurity();
                expectedDirectorySecurity.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(sid, System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
                expectedDirectorySecurity.AddAuditRule(new System.Security.AccessControl.FileSystemAuditRule(sid, System.Security.AccessControl.FileSystemRights.Read, System.Security.AccessControl.AuditFlags.Success));


                using (new Alphaleonis.Win32.Security.PrivilegeEnabler(Alphaleonis.Win32.Security.Privilege.Security))
                {
                    var s1 = System.IO.Directory.CreateDirectory(pathExpected, expectedDirectorySecurity);
                    var s2 = Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(pathActual, expectedDirectorySecurity);


                    var expected = s1.GetAccessControl().GetSecurityDescriptorSddlForm(System.Security.AccessControl.AccessControlSections.All);
                    var actual   = s2.GetAccessControl().GetSecurityDescriptorSddlForm(System.Security.AccessControl.AccessControlSections.All);


                    Console.WriteLine("\tSystem.IO: {0}", expected);
                    Console.WriteLine("\tAlphaFS  : {0}", actual);


                    Assert.AreEqual(expected, actual);
                }
            }

            Console.WriteLine();
        }
Beispiel #17
0
        public static void ClearApplicationTempFolder()
        {
            string tmpFolder = GetDefaultApplicationTempFolder();

            if (System.IO.Directory.Exists(tmpFolder))
            {
                try
                {
                    System.IO.Directory.Delete(tmpFolder, true);
                }
                catch (System.Security.SecurityException)
                {
                    System.IO.DirectoryInfo tmpPathDirInfo = new System.IO.DirectoryInfo(tmpFolder);
                    System.Security.AccessControl.DirectorySecurity dSecurity = tmpPathDirInfo.GetAccessControl();
                    try
                    {
                        bool tryModify = false;
                        dSecurity.ModifyAccessRule(System.Security.AccessControl.AccessControlModification.Reset, 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), out tryModify);
                        if (tryModify)
                        {
                            tmpPathDirInfo.SetAccessControl(dSecurity);
                            tmpPathDirInfo.Delete(true);
                        }
                        else
                        {
                            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);
                            tmpPathDirInfo.Delete(true);
                        }
                    }
                    catch
                    {
                    }
                }
                catch
                {
                }
            }
        }
Beispiel #18
0
        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="logFilePath"></param>
        /// <param name="msg"></param>
        public void WriteLog(string logFilePath, string msg)
        {
            string filePostfix = logFilePath.Substring(logFilePath.LastIndexOf('.') + 1);

            try
            {
                System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(this.LogFileFolderPath);
                if (!dir.Exists)
                {
                    System.Security.AccessControl.DirectorySecurity ds = new System.Security.AccessControl.DirectorySecurity();

                    //Everyone账户
                    System.Security.Principal.SecurityIdentifier sid  = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
                    System.Security.Principal.NTAccount          acct = sid.Translate(typeof(System.Security.Principal.NTAccount)) as System.Security.Principal.NTAccount;
                    ds.AddAccessRule(
                        new System.Security.AccessControl.FileSystemAccessRule(
                            acct
                            , System.Security.AccessControl.FileSystemRights.FullControl
                            , System.Security.AccessControl.AccessControlType.Allow)
                        );
                    dir.Create(ds);
                }
                else
                {
                    System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
                    {
                        DeleteOldFiles();
                    }));
                    t.Start();
                    t.Join();
                }
                if (!string.Equals("txt", filePostfix, StringComparison.OrdinalIgnoreCase))
                {
                    throw new Exception("仅支持txt文件");
                }
                bool bAppend         = true;
                System.IO.FileInfo f = new System.IO.FileInfo(logFilePath);
                if (!f.Exists || f.Length > this.MaxFileSize)//文件太大,清空旧内容
                {
                    bAppend = false;
                }

                lock (objlck)
                {
                    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(logFilePath, bAppend))
                    {
                        string logContent = string.Format("\r\n======================="
                                                          + "\r\n{0}"
                                                          + "\r\n{1}"
                                                          + "\r\n=======================\r\n", DateTime.Now.ToString("[yyyy-MM-dd HH:mm:ss] "), msg);
                        sw.Write(logContent);
                        sw.Flush();
                        sw.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #19
0
        public RootApplication(frmMenu frm)
        {
#if DEBUG
            IsDebug = true;
#endif
            Menu = frm;
            m_Documents.Add(null);             // because the editor will just assign the current document into the current index

            // folders...
            EXEFolder      = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            InternalFolder = EXEFolder;

            SharedFolder = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), AppName);
            ConfigFolder = SharedFolder;
            bool sharedCreated = false;
            // create shared folder and set permissions
            try
            {
                if (!System.IO.Directory.Exists(SharedFolder))
                {
                    System.IO.Directory.CreateDirectory(SharedFolder);
                    System.Security.AccessControl.DirectorySecurity    dirSecurity = System.IO.Directory.GetAccessControl(SharedFolder);
                    System.Security.Principal.SecurityIdentifier       user        = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.BuiltinUsersSid, null);
                    System.Security.AccessControl.FileSystemAccessRule newRule     = new System.Security.AccessControl.FileSystemAccessRule(user, 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);
                    dirSecurity.AddAccessRule(newRule);
                    System.IO.Directory.SetAccessControl(SharedFolder, dirSecurity);

                    sharedCreated = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot create required folder: " + SharedFolder + "\r\n" + "Error: " + ex);
                Application.Exit();
            }

#if DEBUG
            EXEFolder      = "d:\\data\\ace\\SAW\\Installer\\installer files";
            InternalFolder = EXEFolder;
            // config certainly needs to write back to the installation folder
            ConfigFolder = "d:\\data\\ace\\SAW\\test data";
            SharedFolder = "d:\\data\\ace\\SAW\\test data";
#else
            // Temporary version using folder location for everything
            //SharedFolder = EXEFolder + System.IO.Path.DirectorySeparatorChar + "Data";
            //ConfigFolder = SharedFolder;
#endif

            Globals.Root = this;
            try
            {
                Log                      = new CLogFile(SharedFolder + System.IO.Path.DirectorySeparatorChar + "log.txt");
                LogPermanent             = new CLogFile(SharedFolder + System.IO.Path.DirectorySeparatorChar + "permanent.txt", 100000);
                LogPermanent.TimeStampEx = TimeStamps.Date;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Could not create log files: " + ex.Message);
            }
            Log.WriteLine("Starting, version = " + SoftwareVersion.VersionString);
            Log.WriteLine("EXEFolder = " + EXEFolder);
            Log.WriteLine("SharedFolder = " + SharedFolder);
            Log.WriteLine("InternalFolder = " + InternalFolder);
            Log.WriteLine("OS = " + Environment.OSVersion);
            Log.WriteLine("64-bit = " + Environment.Is64BitOperatingSystem);
            Log.WriteLine("CLR = " + Environment.Version);
            Globals.CheckThemeOnStartup();

            if (sharedCreated)
            {
                // need to copy across from Splash 1 if applicable
                LogPermanent.WriteLine("Shared folder created");
            }

            Strings.Load();
            Log.WriteLine("SystemDPI = " + GUIUtilities.SystemDPI);

            Functions.Verb.CreateList();             // must before any configs loaded
            Functions.SAWVerbs.RegisterVerbs();

            // load configurations...
            Config.SystemConfig = LoadConfig("system" + Config.Extension, Config.Levels.System);
            Config.UserUser     = LoadConfig("User" + Config.Extension, Config.Levels.User, "user_Default" + Config.Extension);
            Config.UserUser.EnsureUserResources();
            if (!System.IO.Directory.Exists(Activities.ActivityConfigFolder))
            {
                System.IO.Directory.CreateDirectory(Activities.ActivityConfigFolder);
            }
            // activities are now loaded as needed

#if !DEBUG
            AppDomain.CurrentDomain.UnhandledException += frmErrorReport.UnhandledException;
            Application.ThreadException += frmErrorReport.ThreadException;
#else
            Config.Delta.ApplyV8Changes();
#endif
            CurrentConfig = new AppliedConfig();
            CurrentConfig.AddConfigAtEnd(Config.SystemConfig);
            CurrentConfig.AddConfigWithPriority(Config.UserUser);
        }
        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);
            }
        }
Beispiel #21
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);
            }
        }