Beispiel #1
0
        private void DirectoryInfo_FolderName255Characters(bool isNetwork)
        {
            using (var tempRoot = new TemporaryDirectory(isNetwork))
            {
                var folder = tempRoot.Directory.FullName;

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


                // System.IO: 244, anything higher throws System.IO.PathTooLongException: The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.
                // AlphaFS  : 255, anything higher throws System.IO.PathTooLongException.
                var subFolder = new string('b', 255);


                var local = Alphaleonis.Win32.Filesystem.Path.Combine(folder, subFolder);
                var unc   = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(local);
                Console.WriteLine("SubFolder length: {0}, total path length: {1}", subFolder.Length, isNetwork ? unc.Length : local.Length);

                // Success.
                var di1 = new Alphaleonis.Win32.Filesystem.DirectoryInfo(isNetwork ? unc : local);

                // Fail.
                //var di1 = new System.IO.DirectoryInfo(local);


                di1.Create();
                Assert.IsTrue(di1.Exists);


                UnitTestConstants.Dump(di1, -17);
            }

            Console.WriteLine();
        }
        public override ItemList ProcessShow([NotNull] ShowItem si, bool forceRefresh)
        {
            DateTime?updateTime = si.TheSeries()?.LastAiredDate;

            if (!TVSettings.Instance.CorrectFileDates || !updateTime.HasValue)
            {
                return(null);
            }

            DateTime newUpdateTime = Helpers.GetMinWindowsTime(updateTime.Value);

            DirectoryInfo di = new DirectoryInfo(si.AutoAddFolderBase);

            try
            {
                if (di.LastWriteTimeUtc != newUpdateTime && !doneFilesAndFolders.Contains(di.FullName))
                {
                    doneFilesAndFolders.Add(di.FullName);
                    return(new ItemList {
                        new ActionDateTouch(di, si, newUpdateTime)
                    });
                }
            }
            catch (Exception)
            {
                doneFilesAndFolders.Add(di.FullName);
                return(new ItemList {
                    new ActionDateTouch(di, si, newUpdateTime)
                });
            }
            return(null);
        }
Beispiel #3
0
        private void DirectoryInfo_MoveTo_Rename(bool isNetwork)
        {
            using (var tempRoot = new TemporaryDirectory(isNetwork))
            {
                var newFolderName = "Rename_to_" + tempRoot.RandomDirectoryName;

                var dirInfoAlphaFS = new Alphaleonis.Win32.Filesystem.DirectoryInfo(tempRoot.RandomDirectoryFullPath);

                var dirInfoSystemIO = new System.IO.DirectoryInfo(System.IO.Path.Combine(tempRoot.Directory.FullName, newFolderName));

                Console.WriteLine("Input Directory Path: [{0}]", dirInfoAlphaFS.FullName);
                Console.WriteLine("\n\tRename folder to: [{0}]", dirInfoSystemIO.Name);


                // Create folder.
                dirInfoAlphaFS.Create();


                // Rename folder.
                dirInfoAlphaFS.MoveTo(dirInfoSystemIO.FullName);


                dirInfoAlphaFS.Refresh();
                dirInfoSystemIO.Refresh();


                Assert.IsTrue(dirInfoAlphaFS.Exists, "It is expected that the source exists, but is does not.");

                Assert.AreEqual(dirInfoAlphaFS.Parent.FullName, dirInfoSystemIO.Parent.FullName);
            }

            Console.WriteLine();
        }
Beispiel #4
0
        private void UpdatePreview(List <TVSettings.FilenameProcessorRE> rel)
        {
            lvPreview.BeginUpdate();
            DirectoryInfo d = new DirectoryInfo(txtFolder.Text);

            foreach (FileInfo fi in d.GetFiles())
            {
                if (!TVSettings.Instance.UsefulExtension(fi.Extension, true))
                {
                    continue; // move on
                }
                ShowItem si = cbShowList.SelectedIndex >= 0 ? shows[cbShowList.SelectedIndex] : null;
                bool     r  = TVDoc.FindSeasEp(fi, out int seas, out int ep, out int maxEp, si, rel, false,
                                               out TVSettings.FilenameProcessorRE matchRex);

                ListViewItem lvi = new ListViewItem {
                    Text = fi.Name
                };
                lvi.SubItems.Add((seas == -1) ? "-" : seas.ToString());
                lvi.SubItems.Add((ep == -1) ? "-" : ep + ((maxEp != -1) ? "-" + maxEp : ""));
                lvi.SubItems.Add((matchRex == null) ? "-" : matchRex.Notes);
                if (!r)
                {
                    lvi.BackColor = Helpers.WarningColor();
                }

                lvPreview.Items.Add(lvi);
            }

            lvPreview.EndUpdate();
        }
Beispiel #5
0
        private void DirectoryInfo_Attributes(bool isNetwork)
        {
            using (var tempRoot = new TemporaryDirectory(isNetwork))
            {
                var folder  = tempRoot.RandomDirectoryFullPath;
                var dirInfo = new Alphaleonis.Win32.Filesystem.DirectoryInfo(folder + "-AlphaFS");

                Console.WriteLine("Input Directory Path: [{0}]", dirInfo.FullName);

                dirInfo.Create();


                dirInfo.Attributes |= System.IO.FileAttributes.ReadOnly;
                Assert.IsTrue((dirInfo.Attributes & System.IO.FileAttributes.ReadOnly) != 0, "The directory is not ReadOnly, but is expected to.");

                dirInfo.Attributes &= ~System.IO.FileAttributes.ReadOnly;
                Assert.IsTrue((dirInfo.Attributes & System.IO.FileAttributes.ReadOnly) == 0, "The directory is ReadOnly, but is expected not to.");


                dirInfo.Attributes |= System.IO.FileAttributes.Hidden;
                Assert.IsTrue((dirInfo.Attributes & System.IO.FileAttributes.Hidden) != 0, "The directory is not Hidden, but is expected to.");

                dirInfo.Attributes &= ~System.IO.FileAttributes.Hidden;
                Assert.IsTrue((dirInfo.Attributes & System.IO.FileAttributes.Hidden) == 0, "The directory is Hidden, but is expected not to.");


                dirInfo.Attributes |= System.IO.FileAttributes.System;
                Assert.IsTrue((dirInfo.Attributes & System.IO.FileAttributes.System) != 0, "The directory is not System, but is expected to.");

                dirInfo.Attributes &= ~System.IO.FileAttributes.System;
                Assert.IsTrue((dirInfo.Attributes & System.IO.FileAttributes.System) == 0, "The directory is System, but is expected not to.");
            }

            Console.WriteLine();
        }
Beispiel #6
0
        private void Dispose(bool isDisposing)
        {
            try
            {
                if (isDisposing)
                {
                    System.IO.Directory.Delete(Directory.FullName, true);
                }
            }
            catch
            {
                try
                {
                    var dirInfo = new Alphaleonis.Win32.Filesystem.DirectoryInfo(Directory.FullName, Alphaleonis.Win32.Filesystem.PathFormat.FullPath);

                    if (dirInfo.Exists)
                    {
                        dirInfo.Delete(true, true);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("TemporaryDirectory delete failure. Error: {0}", ex.Message.Replace(Environment.NewLine, string.Empty));
                }
            }
        }
Beispiel #7
0
        public override ItemList ProcessSeason(ShowItem si, string folder, int snum, bool forceRefresh)
        {
            DateTime?newUpdateTime = si.GetSeason(snum).LastAiredDate();

            if (TVSettings.Instance.CorrectFileDates && newUpdateTime.HasValue)
            {
                //Any series before 1980 will get 1980 as the timestamp
                if (newUpdateTime.Value.CompareTo(Helpers.windowsStartDateTime) < 0)
                {
                    newUpdateTime = Helpers.windowsStartDateTime;
                }


                DirectoryInfo di = new DirectoryInfo(folder);
                if ((di.LastWriteTimeUtc != newUpdateTime.Value) && (!this.doneFilesAndFolders.Contains(di.FullName)))
                {
                    this.doneFilesAndFolders.Add(di.FullName);
                    return(new ItemList()
                    {
                        new ActionDateTouch(di, si, newUpdateTime.Value)
                    });
                }
            }
            return(null);
        }
        private void Dispose(bool isDisposing)
        {
            try
            {
                if (isDisposing)
                {
                    System.IO.Directory.Delete(Directory.FullName, true);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("\n\nDelete TemporaryDirectory: [{0}]. Error: [{1}]", Directory.FullName, ex.Message.Replace(Environment.NewLine, string.Empty));
                Console.Write("Retry using AlphaFS... ");

                try
                {
                    var dirInfo = new Alphaleonis.Win32.Filesystem.DirectoryInfo(Directory.FullName, Alphaleonis.Win32.Filesystem.PathFormat.FullPath);
                    if (dirInfo.Exists)
                    {
                        dirInfo.Delete(true, true);
                        Console.WriteLine("Success.");
                    }

                    else
                    {
                        Console.WriteLine("TemporaryDirectory was already removed.");
                    }
                }
                catch (Exception ex2)
                {
                    Console.WriteLine("Delete failure TemporaryDirectory. Error: {0}", ex2.Message.Replace(Environment.NewLine, string.Empty));
                }
            }
        }
Beispiel #9
0
        public override ItemList ProcessSeason([NotNull] ShowItem si, string folder, int snum, bool forceRefresh)
        {
            DateTime?updateTime = si.GetSeason(snum)?.LastAiredDate();

            if (!TVSettings.Instance.CorrectFileDates || !updateTime.HasValue)
            {
                return(null);
            }

            DateTime newUpdateTime = Helpers.GetMinWindowsTime(updateTime.Value);

            DirectoryInfo di = new DirectoryInfo(folder);

            try
            {
                if ((di.LastWriteTimeUtc != newUpdateTime) && (!doneFilesAndFolders.Contains(di.FullName)))
                {
                    doneFilesAndFolders.Add(di.FullName);
                    return(new ItemList()
                    {
                        new ActionDateTouch(di, si, newUpdateTime)
                    });
                }
            }
            catch (Exception)
            {
                doneFilesAndFolders.Add(di.FullName);
                return(new ItemList()
                {
                    new ActionDateTouch(di, si, newUpdateTime)
                });
            }

            return(null);
        }
        public DirectoryInfoWrapper(IFileSystem fileSystem, AfsDirectoryInfo instance) : base(fileSystem)
        {
            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }

            this.instance = instance;
        }
        private void ReviewDirInDownloadDirectory(string subDirPath)
        {
            //we are not checking for any file updates, so can return
            if (!TVSettings.Instance.RemoveDownloadDirectoriesFiles && !TVSettings.Instance.RemoveDownloadDirectoriesFilesMatchMovies)
            {
                return;
            }

            if (!Directory.Exists(subDirPath))
            {
                return;
            }

            DirectoryInfo di = new DirectoryInfo(subDirPath);

            FileInfo?neededFile = filesThatMayBeNeeded.FirstOrDefault(info => info.DirectoryName.Contains(di.FullName));

            if (neededFile != null)
            {
                LOGGER.Info($"Not removing {di.FullName} as it may be needed for {neededFile.FullName}");
                return;
            }

            List <MovieConfiguration> matchingMovies = movieList.Where(mi => mi.NameMatch(di, TVSettings.Instance.UseFullPathNameToMatchSearchFolders)).ToList();

            List <ShowConfiguration> matchingShows = showList.Where(si => si.NameMatch(di, TVSettings.Instance.UseFullPathNameToMatchSearchFolders)).ToList();

            if (!matchingShows.Any() && !matchingMovies.Any())
            {
                return; // Some sort of random file - ignore
            }

            var neededMatchingShows = matchingShows.Where(si => FinderHelper.FileNeeded(di, si, dfc)).ToList();

            if (neededMatchingShows.Any())
            {
                LOGGER.Info($"Not removing {di.FullName} as it may be needed for {neededMatchingShows.Select(x=>x.ShowName).ToCsv()}");
                return;
            }

            var neededMatchingMovie = matchingMovies.Where(si => FinderHelper.FileNeeded(di, si, dfc)).ToList();

            if (neededMatchingMovie.Any())
            {
                LOGGER.Info($"Not removing {di.FullName} as it may be needed for {neededMatchingMovie.Select(x=>x.ShowName).ToCsv()}");
                return;
            }

            if (matchingShows.Count > 0 && TVSettings.Instance.RemoveDownloadDirectoriesFiles)
            {
                returnActions.Add(SetupDirectoryRemoval(di, matchingShows));
            }
            if (matchingMovies.Count > 0 && TVSettings.Instance.RemoveDownloadDirectoriesFilesMatchMovies)
            {
                returnActions.Add(SetupDirectoryRemoval(di, matchingMovies));
            }
        }
        private static Action SetupDirectoryRemoval([NotNull] DirectoryInfo di,
                                                    [NotNull] IReadOnlyList <MovieConfiguration> matchingMovies)
        {
            MovieConfiguration si = matchingMovies[0]; //Choose the first cachedSeries

            LOGGER.Info($"Removing {di.FullName} as it matches {si.ShowName} and no files are needed");

            return(new ActionDeleteDirectory(di, si, TVSettings.Instance.Tidyup));
        }
Beispiel #13
0
        public OriginLibrary(string fullPath, bool isMain = false)
        {
            FullPath      = fullPath;
            IsMain        = isMain;
            Type          = Enums.LibraryType.Origin;
            DirectoryInfo = new DirectoryInfo(fullPath);

            AllowedAppTypes.Add(Enums.LibraryType.Origin);
        }
        private void Directory_SetAccessControl(bool isNetwork)
        {
            using (var tempRoot = new TemporaryDirectory(isNetwork))
            {
                var folder = tempRoot.CreateDirectory();

                var sysIO            = System.IO.Directory.GetAccessControl(folder.FullName);
                var sysIOaccessRules = sysIO.GetAccessRules(true, true, typeof(NTAccount));

                var alphaFS            = Alphaleonis.Win32.Filesystem.Directory.GetAccessControl(folder.FullName);
                var alphaFSaccessRules = alphaFS.GetAccessRules(true, true, typeof(NTAccount));


                Console.WriteLine("Input Directory Path: [{0}]", folder.FullName);
                Console.WriteLine("\n\tSystem.IO rules found: [{0}]\n\tAlphaFS rules found  : [{1}]", sysIOaccessRules.Count, alphaFSaccessRules.Count);
                Assert.AreEqual(sysIOaccessRules.Count, alphaFSaccessRules.Count);


                // Sanity check.
                UnitTestConstants.TestAccessRules(sysIO, alphaFS);


                // Remove inherited properties.
                // Passing true for first parameter protects the new permission from inheritance,
                // and second parameter removes the existing inherited permissions
                Console.WriteLine("\n\tRemove inherited properties and persist it.");
                alphaFS.SetAccessRuleProtection(true, false);
                Alphaleonis.Win32.Filesystem.Directory.SetAccessControl(folder.FullName, alphaFS, AccessControlSections.Access);


                // Re-read, using instance methods.
                var sysIOdi   = new System.IO.DirectoryInfo(folder.FullName);
                var alphaFSdi = new Alphaleonis.Win32.Filesystem.DirectoryInfo(folder.FullName);

                sysIO   = sysIOdi.GetAccessControl(AccessControlSections.Access);
                alphaFS = alphaFSdi.GetAccessControl(AccessControlSections.Access);

                // Sanity check.
                UnitTestConstants.TestAccessRules(sysIO, alphaFS);


                // Restore inherited properties.
                Console.WriteLine("\n\tRestore inherited properties and persist it.");
                alphaFS.SetAccessRuleProtection(false, true);
                Alphaleonis.Win32.Filesystem.Directory.SetAccessControl(folder.FullName, alphaFS, AccessControlSections.Access);


                // Re-read.
                sysIO   = System.IO.Directory.GetAccessControl(folder.FullName, AccessControlSections.Access);
                alphaFS = Alphaleonis.Win32.Filesystem.Directory.GetAccessControl(folder.FullName, AccessControlSections.Access);

                // Sanity check.
                UnitTestConstants.TestAccessRules(sysIO, alphaFS);
            }

            Console.WriteLine();
        }
Beispiel #15
0
        static void DeleteDirectory(string dir)
        {
            Alphaleonis.Win32.Filesystem.DirectoryInfo di = new Alphaleonis.Win32.Filesystem.DirectoryInfo(dir);

            RemoveReadonlyAttribute(di);

            di.Delete(true);

            return;
        }
Beispiel #16
0
        private async Task InstallManualGameFiles()
        {
            if (!ModList.Directives.Any(d => d.To.StartsWith(Consts.ManualGameFilesDir)))
            {
                return;
            }

            var result = await Utils.Log(new YesNoIntervention("Some mods from this ModList must be installed directly into " +
                                                               "the game folder. Do you want to do this manually or do you want Wabbajack " +
                                                               "to do this for you?", "Move mods into game folder?")).Task;

            if (result != ConfirmationIntervention.Choice.Continue)
            {
                return;
            }

            var manualFilesDir = Path.Combine(OutputFolder, Consts.ManualGameFilesDir);

            var gameFolder = GameInfo.GameLocation();

            Info($"Copying files from {manualFilesDir} " +
                 $"to the game folder at {gameFolder}");

            if (!Directory.Exists(manualFilesDir))
            {
                Info($"{manualFilesDir} does not exist!");
                return;
            }

            await Directory.EnumerateDirectories(manualFilesDir).PMap(Queue, dir =>
            {
                var dirInfo = new DirectoryInfo(dir);
                dirInfo.GetDirectories("*", SearchOption.AllDirectories).Do(d =>
                {
                    var destPath = d.FullName.Replace(manualFilesDir, gameFolder);
                    Status($"Creating directory {destPath}");
                    Directory.CreateDirectory(destPath);
                });

                dirInfo.GetFiles("*", SearchOption.AllDirectories).Do(f =>
                {
                    var destPath = f.FullName.Replace(manualFilesDir, gameFolder);
                    Status($"Copying file {f.FullName} to {destPath}");
                    try
                    {
                        File.Copy(f.FullName, destPath);
                    }
                    catch (Exception)
                    {
                        Info($"Could not copy file {f.FullName} to {destPath}. The file may already exist, skipping...");
                    }
                });
            });
        }
Beispiel #17
0
        private void Directory_CreateSymbolicLink_And_GetLinkTargetInfo(bool isNetwork)
        {
            UnitTestConstants.PrintUnitTestHeader(isNetwork);

            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 folderLink = System.IO.Path.Combine(rootDir.Directory.FullName, "FolderLink-ToDestinationFolder");

                var dirInfo = new System.IO.DirectoryInfo(System.IO.Path.Combine(rootDir.Directory.FullName, "DestinationFolder"));
                dirInfo.Create();

                Console.WriteLine("\nInput Directory Path: [{0}]", dirInfo.FullName);
                Console.WriteLine("Input Directory Link: [{0}]", folderLink);


                Alphaleonis.Win32.Filesystem.Directory.CreateSymbolicLink(folderLink, dirInfo.FullName);


                var lvi = Alphaleonis.Win32.Filesystem.Directory.GetLinkTargetInfo(folderLink);
                UnitTestConstants.Dump(lvi, -14);
                Assert.IsTrue(lvi.PrintName.Equals(dirInfo.FullName, StringComparison.OrdinalIgnoreCase));



                var dirInfoSysIO = new System.IO.DirectoryInfo(folderLink);
                UnitTestConstants.Dump(dirInfoSysIO, -17);

                Assert.IsTrue((dirInfoSysIO.Attributes & System.IO.FileAttributes.ReparsePoint) != 0);



                var alphaFSDirInfo = new Alphaleonis.Win32.Filesystem.DirectoryInfo(folderLink);
                UnitTestConstants.Dump(alphaFSDirInfo.EntryInfo, -19);

                Assert.AreEqual(System.IO.Directory.Exists(alphaFSDirInfo.FullName), alphaFSDirInfo.Exists);
                Assert.IsTrue(alphaFSDirInfo.EntryInfo.IsDirectory);
                Assert.IsFalse(alphaFSDirInfo.EntryInfo.IsMountPoint);
                Assert.IsTrue(alphaFSDirInfo.EntryInfo.IsReparsePoint);
                Assert.IsTrue(alphaFSDirInfo.EntryInfo.IsSymbolicLink);
                Assert.AreEqual(alphaFSDirInfo.EntryInfo.ReparsePointTag, Alphaleonis.Win32.Filesystem.ReparsePointTag.SymLink);
            }

            Console.WriteLine();
        }
Beispiel #18
0
        private void DirectoryInfo_Refresh(bool isNetwork)
        {
            using (var tempRoot = new TemporaryDirectory(isNetwork))
            {
                var folder    = tempRoot.RandomDirectoryFullPath;
                var diSysIo   = new System.IO.DirectoryInfo(folder + "-System.IO");
                var diAlphaFS = new Alphaleonis.Win32.Filesystem.DirectoryInfo(folder + "-AlphaFS");

                Console.WriteLine("System.IO Input Directory Path: [{0}]", diSysIo.FullName);
                Console.WriteLine("AlphaFS   Input Directory Path: [{0}]", diAlphaFS.FullName);


                var existsSysIo = diSysIo.Exists;
                var exists      = diAlphaFS.Exists;
                Assert.AreEqual(existsSysIo, exists);
                Assert.IsFalse(exists, "The directory exists, but is expected not to.");


                diSysIo.Create();
                diAlphaFS.Create();
                existsSysIo = diSysIo.Exists;
                exists      = diAlphaFS.Exists;
                Assert.AreEqual(existsSysIo, exists);
                Assert.IsFalse(exists, "The directory exists, but is expected not to.");


                diSysIo.Refresh();
                diAlphaFS.Refresh();
                existsSysIo = diSysIo.Exists;
                exists      = diAlphaFS.Exists;
                Assert.AreEqual(existsSysIo, exists);
                Assert.IsTrue(exists, "The directory does not exists, but is expected to.");


                diSysIo.Delete();
                diAlphaFS.Delete();
                existsSysIo = diSysIo.Exists;
                exists      = diAlphaFS.Exists;
                Assert.AreEqual(existsSysIo, exists);
                Assert.IsTrue(exists, "The directory does not exists, but is expected to.");


                diSysIo.Refresh();
                diAlphaFS.Refresh();
                existsSysIo = diSysIo.Exists;
                exists      = diAlphaFS.Exists;
                Assert.AreEqual(existsSysIo, exists);
                Assert.IsFalse(exists, "The directory exists, but is expected not to.");
            }

            Console.WriteLine();
        }
        private void DirectoryInfo_CatchPathTooLongException_FolderNameGreaterThan255Characters(bool isNetwork)
        {
            UnitTestConstants.PrintUnitTestHeader(isNetwork);

            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.Directory.FullName;


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


                // System.IO: 244, anything higher throws System.IO.PathTooLongException: The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.
                // AlphaFS  : 255, anything higher throws System.IO.PathTooLongException.
                var subFolder = new string('b', 256);


                var local = Alphaleonis.Win32.Filesystem.Path.Combine(folder, subFolder);
                var unc   = Alphaleonis.Win32.Filesystem.Path.LocalToUnc(local);
                Console.WriteLine("SubFolder length: {0}, total path length: {1}", subFolder.Length, isNetwork ? unc.Length : local.Length);
                Console.WriteLine();


                var gotException = false;

                try
                {
                    // Fail.
                    var di1 = new Alphaleonis.Win32.Filesystem.DirectoryInfo(isNetwork ? unc : local);
                }
                catch (Exception ex)
                {
                    var exName = ex.GetType().Name;
                    gotException = exName.Equals("PathTooLongException", StringComparison.OrdinalIgnoreCase);
                    Console.WriteLine("\tCaught EXPECTED Exception: [{0}] Message: [{1}]", exName, ex.Message);
                }


                Assert.IsTrue(gotException, "The exception is not caught, but is expected to.");
            }

            Console.WriteLine();
        }
Beispiel #20
0
        public void DirectoryInfo_AnalyzeSecurity_LocalAcess_ShouldNotExist()
        {
            var testDir = GetTempDirectoryName();
             SetSecuritySystem(testDir);
             var dirsec = new System.IO.DirectoryInfo(testDir + @"\inherited").GetAccessControl();
             var accessRules = dirsec.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
             Assert.IsFalse(HasLocalAces(accessRules), "local access rules found");

             testDir = GetTempDirectoryName();
             SetSecurityAlpha(testDir);
             dirsec = new Alphaleonis.Win32.Filesystem.DirectoryInfo(testDir + @"\inherited").GetAccessControl();
             accessRules = dirsec.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
             Assert.IsFalse(HasLocalAces(accessRules), "local access rules found");
        }
Beispiel #21
0
 public void DeleteDir(string path)
 {
     try
     {
         Alphaleonis.Win32.Filesystem.DirectoryInfo di = new Alphaleonis.Win32.Filesystem.DirectoryInfo(path);
         if (di.Exists)
         {
             di.Delete(true);
         }
     }
     catch (System.Exception ex)
     {
         LogManager.WriteLog(LogFile.System, MessageUtil.GetExceptionMsg(ex, ""));
     }
 }
Beispiel #22
0
        private void SetSecurityAlpha(string directory)
        {
            if (System.IO.Directory.Exists(directory))
            System.IO.Directory.Delete(directory, true);
             System.IO.Directory.CreateDirectory(directory);
             System.IO.Directory.CreateDirectory(System.IO.Path.Combine(directory, "inherited"));

             var testDirInfo = new Alphaleonis.Win32.Filesystem.DirectoryInfo(directory);

             var ds = testDirInfo.GetAccessControl(System.Security.AccessControl.AccessControlSections.Access);
             ds.SetAccessRuleProtection(true, false);
             ds.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null), 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));

             testDirInfo.SetAccessControl(ds);
        }
Beispiel #23
0
        public static bool Same(DirectoryInfo a, DirectoryInfo b)
        {
            string n1 = a.FullName;
            string n2 = b.FullName;

            if (!n1.EndsWith(Path.DirectorySeparatorChar.ToString()))
            {
                n1 = n1 + Path.DirectorySeparatorChar;
            }
            if (!n2.EndsWith(Path.DirectorySeparatorChar.ToString()))
            {
                n2 = n2 + Path.DirectorySeparatorChar;
            }

            return(String.Compare(n1, n2, true) == 0); // true->ignore case
        }
Beispiel #24
0
        public PossibleNewMovie(FileInfo possibleMovieFile, bool andGuess, bool showErrorMsgBox)
        {
            MovieStub = possibleMovieFile.MovieFileNameBase();
            Directory = possibleMovieFile.Directory;

            (string?directoryRefinedHint, int?directoryPossibleYear) = GuessShowName(possibleMovieFile.Directory.Name);
            (string?fileRefinedHint, int?filePossibleYear)           = GuessShowName(possibleMovieFile.MovieFileNameBase());

            RefinedHint  = fileRefinedHint.HasValue() ? fileRefinedHint : directoryRefinedHint;
            PossibleYear = filePossibleYear ?? directoryPossibleYear;

            if (andGuess)
            {
                GuessMovie(showErrorMsgBox);
            }
        }
 public static bool IsDirectoryAccessible(this DirectoryInfo directory)
 {
     try
     {
         directory.GetAccessControl();
         return(true);
     }
     catch (UnauthorizedAccessException)
     {
         return(true);
     }
     catch
     {
         return(false);
     }
 }
        public SteamAppInfo(int appId, Library library, DirectoryInfo installationDirectory)
        {
            AppId   = appId;
            Library = library;
            InstallationDirectory = installationDirectory;
            GameHeaderImage       = $"http://cdn.akamai.steamstatic.com/steam/apps/{AppId}/header.jpg";

            CompressedArchivePath = new FileInfo(Path.Combine(Library.DirectoryList["SteamApps"].FullName, AppId + ".zip"));

            AdditionalDirectories.Add((new DirectoryInfo(Path.Combine(Library.DirectoryList["Download"].FullName, InstallationDirectory.Name)), "*", SearchOption.AllDirectories));
            AdditionalDirectories.Add((new DirectoryInfo(Path.Combine(Library.DirectoryList["Workshop"].FullName, "content", AppId.ToString())), "*", SearchOption.AllDirectories));
            AdditionalDirectories.Add((Library.DirectoryList["Download"], $"*{AppId}*.patch", SearchOption.TopDirectoryOnly));

            AdditionalFiles.Add(new FileInfo(Path.Combine(Library.DirectoryList["SteamApps"].FullName, $"appmanifest_{AppId}.acf")));
            AdditionalFiles.Add(new FileInfo(Path.Combine(Library.DirectoryList["Workshop"].FullName, $"appworkshop_{AppId}.acf")));
        }
Beispiel #27
0
 public static void ParseAppDetails(string name, DirectoryInfo installationDirectory, Definitions.UplayLibrary library, bool isCompressed = false)
 {
     try
     {
         var gameDetails = Definitions.List.UplayConfigurations.FirstOrDefault(x => x.Name == name);
         if (gameDetails != null)
         {
             library.Apps.Add(new Definitions.UplayAppInfo(library, gameDetails.Name, gameDetails.SpaceId, installationDirectory, gameDetails.ThumbImage, isCompressed));
         }
     }
     catch (Exception ex)
     {
         Logger.Fatal(ex);
         MessageBox.Show(ex.ToString());
     }
 }
Beispiel #28
0
        private void DirectoryInfo_Attributes(bool isNetwork)
        {
            UnitTestConstants.PrintUnitTestHeader(isNetwork);

            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;
                var dirInfo = new Alphaleonis.Win32.Filesystem.DirectoryInfo(folder + "-AlphaFS");

                Console.WriteLine("\nAlphaFS Input Directory Path: [{0}]", dirInfo.FullName);

                dirInfo.Create();


                dirInfo.Attributes |= System.IO.FileAttributes.ReadOnly;
                Assert.IsTrue((dirInfo.Attributes & System.IO.FileAttributes.ReadOnly) != 0, "The directory is not ReadOnly, but is expected to.");

                dirInfo.Attributes &= ~System.IO.FileAttributes.ReadOnly;
                Assert.IsTrue((dirInfo.Attributes & System.IO.FileAttributes.ReadOnly) == 0, "The directory is ReadOnly, but is expected not to.");


                dirInfo.Attributes |= System.IO.FileAttributes.Hidden;
                Assert.IsTrue((dirInfo.Attributes & System.IO.FileAttributes.Hidden) != 0, "The directory is not Hidden, but is expected to.");

                dirInfo.Attributes &= ~System.IO.FileAttributes.Hidden;
                Assert.IsTrue((dirInfo.Attributes & System.IO.FileAttributes.Hidden) == 0, "The directory is Hidden, but is expected not to.");


                dirInfo.Attributes |= System.IO.FileAttributes.System;
                Assert.IsTrue((dirInfo.Attributes & System.IO.FileAttributes.System) != 0, "The directory is not System, but is expected to.");

                dirInfo.Attributes &= ~System.IO.FileAttributes.System;
                Assert.IsTrue((dirInfo.Attributes & System.IO.FileAttributes.System) == 0, "The directory is System, but is expected not to.");
            }

            Console.WriteLine();
        }
Beispiel #29
0
        public override ItemList ProcessSeason(ShowItem si, string folder, int snum, bool forceRefresh)
        {
            DateTime?newUpdateTime = si.TheSeries().Seasons[snum].LastAiredDate();

            if (TVSettings.Instance.CorrectFileDates && newUpdateTime.HasValue)
            {
                DirectoryInfo di = new DirectoryInfo(folder);
                if ((di.LastWriteTimeUtc != newUpdateTime.Value) && (!this.doneFilesAndFolders.Contains(di.FullName)))
                {
                    this.doneFilesAndFolders.Add(di.FullName);
                    return(new ItemList()
                    {
                        new ItemDateTouch(di, si, newUpdateTime.Value)
                    });
                }
            }
            return(null);
        }
Beispiel #30
0
        private void ProcessDirectory([NotNull] DirectoryInfo droppedDir)
        {
            if ((droppedDir.Attributes & FileAttributes.Directory) != FileAttributes.Directory)
            {
                Logger.Error($"{droppedDir.FullName} is not a directory, CONTACT DEV TEAM.");
                return;
            }

            foreach (FileInfo subFile in droppedDir.GetFiles())
            {
                ProcessUnknown(subFile);
            }

            foreach (DirectoryInfo subFile in droppedDir.GetDirectories())
            {
                ProcessDirectory(subFile);
            }
        }
Beispiel #31
0
 /// <summary>
 /// 服务器文件列表与本地对比,逻辑如下:
 /// 1.如果服务器存在,本地不存在:
 ///     1.1) 如果文件状态为Deleted,跳过
 ///     1.2) 否则,下载
 /// 2.如果本地存在,服务器不存在,则上传
 /// 3.如果都存在,比较更新时间:
 ///     3.1) 如果本地较新,则上传,并置文件状态为Modified
 ///     3.2) 如果服务器较新:
 ///         3.2.1) 如果文件状态为Deleted,则删除本地文件
 ///         3.2.2) 否则,下载文件
 /// </summary>
 /// <param name="path"></param>
 /// <param name="parentFolder"></param>
 private void BrowseAndUpdateTree(String path, String parentFolder)
 {
     try
     {
         var dirInfo = new DirectoryInfo(path);
         var localFileList = dirInfo.GetFiles();
         foreach (var file in localFileList)
         {
             var localFile = new FileNode
                 {
                     Id = Guid.NewGuid().ToStringEx(),
                     RelativePath = parentFolder,
                     Name = file.Name,
                     Length = file.Length,
                     UpdateTime = file.LastWriteTimeUtc.Ticks,
                     Status = FileStatus.Added
                 };
             var serverFile = serverTree.FileList.FirstOrDefault(item => item.Name.Equals(file.Name));
             if (serverFile == null) //condition 2
             {
                 logger.Debug("Added upload, {0}.", localFile.Name);
                 uploadFileList.Add(localFile);
                 serverTree.FileList.Add(localFile);
             }
             else //condition 3
             {
                 if (serverFile.UpdateTime > localFile.UpdateTime) //condition 3.2
                 {
                     if (serverFile.Status == FileStatus.Deleted) //condition 3.2.1
                     {
                         logger.Debug("Deleted, {0}.", localFile.Name);
                         File.Delete(file.FullName);
                     }
                     else //condition 3.2.2
                     {
                         logger.Debug("Added download, {0}.", localFile.Name);
                         downloadFileList.Add(serverFile);
                     }
                 }
                 else //condition 3.1
                 {
                     logger.Debug("Add upload, {0}.", localFile.Name);
                     serverFile.UpdateTime = localFile.UpdateTime;
                     serverFile.Status = FileStatus.Modified;
                     uploadFileList.Add(localFile);
                 }
             }
         }
         foreach (var serverFile in serverTree.FileList)
         {
             var localFile = localFileList.FirstOrDefault(item => item.Name.Equals(serverFile.Name));
             if (localFile == null && serverFile.Status != FileStatus.Deleted) //condition 1.2
             {
                 logger.Debug("Added download, {0}.", serverFile.Name);
                 downloadFileList.Add(serverFile);
             }
         }
         dirInfo.GetDirectories().ForEach(item => BrowseAndUpdateTree(item.DirectoryName, parentFolder + "\\" + item.Name));
     }
     catch (Exception e)
     {
         logger.Debug("Error occurred when browsing folder, info: {0}.", e);
     }
 }
        protected virtual void Dispose(bool disposing)
        {
            if (_isDisposed)
            {
                return;
            }
            int waitCounter = 1;

            while (!_processId.HasValue)
            {
                Thread.Sleep(TimeSpan.FromMilliseconds(50));
                Console.WriteLine("Waiting {0} milliseconds", 50*waitCounter);
                waitCounter++;
            }

            Console.WriteLine("Disposing IIS Express process");

            if (disposing)
            {
                int? pid;

                if (_process != null)
                {
                    pid = _process.Id;
                    Console.WriteLine("Closed IIS Express");
                    if (!_process.HasExited)
                    {
                        _process.Kill();
                    }

                    using (_process)

                        Console.WriteLine("Disposed IIS Express");
                    {
                    }
                }
                else
                {
                    pid = _processId;
                    Console.WriteLine("Process is null");
                }

                if (pid != null)
                {
                    try
                    {
                        Process process = Process.GetProcessById(pid.Value);

                        using (process)
                        {
                            Console.WriteLine("Killing IIS Express");
                            if (!process.HasExited)
                            {
                                process.Kill();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.Error.WriteLine("Could not kill process with id {0}, {1}", pid, ex);
                    }
                }
                else
                {
                    Console.WriteLine("Could not find any process id to kill");
                }
            }

            if (_removeSiteOnExit)
            {
                try
                {
                    if (WebsitePath.Exists)
                    {
                        var directoryInfo = new DirectoryInfo(WebsitePath.FullName);

                        directoryInfo.Delete(true);
                    }
                }
                catch (IOException ex)
                {
                    throw new IOException("Could not delete the website path '" + WebsitePath.FullName + "'", ex);
                }
            }

            _process = null;
            _processId = null;
            _isDisposed = true;
        }
        public static int CopyTo(this DirectoryInfo sourceDirectory, DirectoryInfo destinationDirectory,
                                  bool copySubDirectories = true, IEnumerable<Predicate<FileInfo>> filesToExclude = null, IEnumerable<string> directoriesToExclude = null)
        {
            var copiedItems = 0;

            if (sourceDirectory == null)
            {
                throw new ArgumentNullException(nameof(sourceDirectory));
            }

            if (destinationDirectory == null)
            {
                throw new ArgumentNullException(nameof(destinationDirectory));
            }

            if (!sourceDirectory.Exists)
            {
                throw new DirectoryNotFoundException(
                    $"Source directory does not exist or could not be found: {sourceDirectory.FullName}");
            }

            var filePredicates = filesToExclude ?? new List<Predicate<FileInfo>>();
            var excludedDirectories = directoriesToExclude ?? new List<string>();

            if (destinationDirectory.Exists)
            {
                if (!destinationDirectory.IsEmpty())
                {
                    var fileCount = destinationDirectory.GetFiles().Length;
                    var directoryCount = destinationDirectory.GetDirectories().Length;
                    throw new IOException(
                        $"The folder '{destinationDirectory.FullName}' cannot be used as a target folder since there are {fileCount} files and {directoryCount} folders in the folder");
                }
            }
            else
            {
                destinationDirectory.Create();
                copiedItems++;
            }

            var files = sourceDirectory.EnumerateFiles().Where(file => filePredicates.All(predicate => !predicate(file))).ToList();

            foreach (FileInfo file in files)
            {
                var temppath = Path.Combine(destinationDirectory.FullName, file.Name);
                Debug.WriteLine($"Copying file '{file.Name}' to '{temppath.FullName}'");
                file.CopyTo(temppath.FullName, false);
                copiedItems++;
            }

            if (copySubDirectories)
            {
                DirectoryInfo[] subDirectory = sourceDirectory.GetDirectories();

                foreach (DirectoryInfo subdir in subDirectory)
                {
                    if (
                        !excludedDirectories.Any(
                            excluded => subdir.Name.Equals(excluded, StringComparison.InvariantCultureIgnoreCase)))
                    {
                        var subDirectoryTempPath = Path.Combine(destinationDirectory.FullName, subdir.Name);

                        var subDirectoryInfo = new DirectoryInfo(subDirectoryTempPath.FullName);

                        Debug.WriteLine($"Copying directory '{subDirectoryInfo.Name}' to '{subDirectoryTempPath.FullName}'");

                        copiedItems += subdir.CopyTo(subDirectoryInfo, copySubDirectories, filesToExclude, directoriesToExclude);
                    }
                }
            }
            return copiedItems;
        }
        public HgRepository(string path, HgEncoder hgEncoder)
        {
            Encoder = hgEncoder;

            basePath = path.ToLowerInvariant().EndsWith(".hg") ? 
                path : 
                Path.Combine(path, ".hg");
            var storeBasePath = Path.Combine(basePath, "store");
            FullPath = new Alphaleonis.Win32.Filesystem.DirectoryInfo(basePath).Parent.FullName;

            fileSystem = new HgFileSystem();
            atomicFileSystem = new HgTransactionalFileSystem();

            Requirements = new HgRequirementsReader(fileSystem).ReadRequirements(Path.Combine(basePath, "requires"));

            store = new HgStoreFactory().CreateInstance(storeBasePath, Requirements, fileSystem, Encoder);
            branchManager = new HgBranchManager(this, fileSystem);
            bookmarkManager = new HgBookmarkManager(this, fileSystem);

            //
            // Make sure it looks more or less like a repository.
            if(!Directory.Exists(basePath)) throw new IOException(basePath);

            var hgRcReader = new HgRcReader();
            var hgRc = hgRcReader.ReadHgRc(Path.Combine(basePath, "hgrc"));
            Rc = hgRc;

            tagManager = new HgTagManager(this, fileSystem);
        }