예제 #1
0
        private DirectoryState DeleteDirectoryTree([NotNull] DirectoryEntry directory, bool isRecursive,
                                                   [NotNull] ErrorRecorder recorder)
        {
            var state = new DirectoryState(recorder);

            if (isRecursive)
            {
                state.MarkHasRead();

                foreach (BaseEntry entry in directory.EnumerateEntries(EnumerationFilter.All).OrderBy(x => x.Name).ToArray())
                {
                    if (entry is FileEntry file)
                    {
                        DeleteSingleFile(file, state);
                    }
                    else if (entry is DirectoryEntry subdirectory)
                    {
                        DirectoryState subState = DeleteDirectoryTree(subdirectory, true, recorder);
                        state.PropagateSubdirectoryState(subState);
                    }
                }
            }

            if (state.AccessKinds != FileAccessKinds.None)
            {
                Container.ChangeTracker.NotifyContentsAccessed(directory.PathFormatter, state.AccessKinds);
            }

            DeleteSingleDirectory(directory, state);

            return(state);
        }
예제 #2
0
        public void MarkAsUnknown()
        {
            state = DirectoryState.Unknown;

            if (FileSystemQueryable.Debug)
            {
                Log.Debug("Reset {0} to {1}", this, state);
            }
        }
예제 #3
0
        public void MarkAsUncrawlable()
        {
            state = DirectoryState.Uncrawlable;

            if (FileSystemQueryable.Debug)
            {
                Log.Debug("Marked {0} as {1}", this, state);
            }
        }
예제 #4
0
        static void Main(string[] args)
        {
            //list with parts of path
            List <string> partOfAllPath = new List <string>()
            {
                @"C:\"
            };

            while (true)
            {
                //create full path from list
                string        path             = string.Join(@"\", partOfAllPath.Select(x => x));
                DirectoryInfo currentDirectiry = GetInfo.GetDirectory(path);
                //Show all directories
                DirectoryState.ShowDirectories(GetInfo.GetDirectoriesFromSomePath(currentDirectiry));
                //Show all documents
                DirectoryState.ShowFiles(GetInfo.GetFilesFromSomePath(currentDirectiry));
                //get value from user
                Console.Write($"{path}\\");
                string userValue = Console.ReadLine();
                //check: user select directory or file
                bool isDirectory = GetInfo.GetDirectoriesFromSomePath(currentDirectiry).Any(x => x.Name.Equals(userValue));
                bool isFile      = GetInfo.GetFilesFromSomePath(currentDirectiry).Any(x => x.Name.Equals(userValue));

                //if directory, we add new part of path to list and in the next step we have new path
                if (isDirectory)
                {
                    partOfAllPath.Add(userValue);
                }
                //if file, create full path to file and show data from file
                else if (isFile)
                {
                    string s = string.Join(@"\", partOfAllPath.Select(x => x));
                    ShowDataFromFile.ShowDataInFile(s + $"\\{userValue}");
                }
                //if ".." we delete last part of path and return to previous directory
                else if (userValue == "..")
                {
                    if (partOfAllPath.Count < 2)
                    {
                        Console.WriteLine("\nIt is root directory\n");
                    }
                    else
                    {
                        partOfAllPath.RemoveAt(partOfAllPath.Count - 1);
                    }
                }
                //No equals names in directory and files
                else
                {
                    Console.WriteLine("\nNo equals names\n");
                }
            }
        }
예제 #5
0
            public void PropagateSubdirectoryState([NotNull] DirectoryState subdirectoryState)
            {
                Guard.NotNull(subdirectoryState, nameof(subdirectoryState));

                if (!subdirectoryState.CanBeDeleted)
                {
                    CanBeDeleted = false;
                }

                if (subdirectoryState.AccessKinds.HasFlag(FileAccessKinds.Write))
                {
                    MarkHasWritten();
                }
            }
예제 #6
0
		private DirectoryModel (FileAttributes attr)
		{
			// Always assume an unknown state
			this.state = DirectoryState.Unknown;

			if (attr != null) {
				this.unique_id = attr.UniqueId;
				
				// Since we don't use the Mtime on directories,
				// we can safely store the last crawl time in it.
				this.last_crawl_time = attr.LastWriteTime;
			}
			
			this.cached_full_name = null;
			this.cached_depth = -1;
		}
예제 #7
0
        private DirectoryModel(FileAttributes attr)
        {
            // Always assume an unknown state
            this.state = DirectoryState.Unknown;

            if (attr != null)
            {
                this.unique_id = attr.UniqueId;

                // Since we don't use the Mtime on directories,
                // we can safely store the last crawl time in it.
                this.last_crawl_time = attr.LastWriteTime;
            }

            this.cached_full_name = null;
            this.cached_depth     = -1;
        }
예제 #8
0
 private static void DeleteSingleFile([NotNull] FileEntry file, [NotNull] DirectoryState state)
 {
     if (file.IsOpen())
     {
         string path = file.PathFormatter.GetPath().GetText();
         state.SetError(ErrorFactory.System.FileIsInUse(path));
     }
     else if (file.Attributes.HasFlag(FileAttributes.ReadOnly))
     {
         state.SetError(ErrorFactory.System.UnauthorizedAccess(file.Name));
     }
     else
     {
         file.Parent.DeleteFile(file.Name, true);
         state.MarkHasWritten();
     }
 }
예제 #9
0
        ///////////////////////////////////////////////////////////

        public void MarkAsClean()
        {
            // If we aren't being watched, the "cleanest"
            // state we can be in is PossiblyClean.
            if (watch_handle == null)
            {
                state = DirectoryState.PossiblyClean;
            }
            else
            {
                state = DirectoryState.Clean;
            }

            if (FileSystemQueryable.Debug)
            {
                Log.Debug("Marked {0} as {1}", this, state);
            }
        }
예제 #10
0
        private static void DeleteSingleDirectory([NotNull] DirectoryEntry directory, [NotNull] DirectoryState state)
        {
            if (directory.Attributes.HasFlag(FileAttributes.ReadOnly))
            {
                string path = directory.PathFormatter.GetPath().GetText();
                state.SetError(ErrorFactory.System.AccessDenied(path));
            }

            if (state.CanBeDeleted)
            {
                directory.Parent?.DeleteDirectory(directory.Name);
            }
        }
예제 #11
0
 public void Snapshot()
 {
     foreach (var child in new List<DirectoryStructureEntry>(Children))
       {
     if (child.State == DirectoryState.Deleted)
       Children.Remove(child);
       }
       foreach (var child in Children)
     child.Snapshot();
       State = DirectoryState.Unchanged;
       PreviousSize = CurrentSize;
 }
예제 #12
0
        private DirectoryState GetState(DirectoryCleanupConfig config)
        {
            var state = new DirectoryState
            {
                Config = config
            };
            DirectoryInfo directoryInfo;

            try
            {
                directoryInfo = new DirectoryInfo(config.FullPath);
            }
            catch (PathTooLongException)
            {
                state.PathTooLong = true;
                return(state);
            }
            catch (ArgumentException)
            {
                state.InvalidPath = true;
                return(state);
            }

            state.Exists = directoryInfo.Exists;

            if (directoryInfo.Exists)
            {
                DateTime?lastWriteTime = null;

                try
                {
                    lastWriteTime = Directory.GetLastWriteTime(config.FullPath);
                }
                catch (UnauthorizedAccessException e)
                {
                    state.Unauthorized = true;
                }

                var lastCleanupTime       = config.LastCleanupTime ?? lastWriteTime ?? DateTime.MinValue;
                var correctedMaxAgeInDays = Math.Max(config.MaxAge, minAge.TotalDays);
                var expiration            = lastCleanupTime.AddDays(correctedMaxAgeInDays);
                state.ExpirationTime = expiration;

                var hasFilter = !string.IsNullOrWhiteSpace(config.Filter);

                var includeFiles = config.CleanupTarget == CleanupTarget.All ||
                                   config.CleanupTarget == CleanupTarget.Files;
                var includeSubDirectories = config.CleanupTarget == CleanupTarget.All ||
                                            config.CleanupTarget == CleanupTarget.Directories;

                if (includeFiles)
                {
                    var files = hasFilter ? directoryInfo.GetFiles(config.Filter) : directoryInfo.GetFiles();
                    state.NumberOfFiles = files.Length;
                }

                if (includeSubDirectories)
                {
                    var subDirs = hasFilter
                        ? directoryInfo.GetDirectories(config.Filter)
                        : directoryInfo.GetDirectories();
                    state.NumberOfSubDirectories = subDirs.Length;
                }

                state.NumberOfChildren = state.NumberOfSubDirectories + state.NumberOfFiles;
            }

            return(state);
        }
예제 #13
0
		public void MarkAsUnknown ()
		{
			state = DirectoryState.Unknown;

			if (FileSystemQueryable.Debug)
				Log.Debug ("Reset {0} to {1}", this, state);
		}
예제 #14
0
		public void MarkAsUncrawlable ()
		{
			state = DirectoryState.Uncrawlable;
			
			if (FileSystemQueryable.Debug)
				Log.Debug ("Marked {0} as {1}", this, state);
		}
예제 #15
0
		///////////////////////////////////////////////////////////

		public void MarkAsClean ()
		{
			// If we aren't being watched, the "cleanest"
			// state we can be in is PossiblyClean.
			if (watch_handle == null)
				state = DirectoryState.PossiblyClean;
			else
				state = DirectoryState.Clean;

			if (FileSystemQueryable.Debug)
				Log.Debug ("Marked {0} as {1}", this, state);
		}
예제 #16
0
		private void Recrawl_Recursive (DirectoryModel dir, DirectoryState state)
		{
			dir.State = state;
			tree_crawl_task.Add (dir);
			foreach (DirectoryModel sub_dir in dir.Children) 
				Recrawl_Recursive (sub_dir, state);
		}
예제 #17
0
        private async void CleanUpDirectory(DirectoryState record)
        {
            string[] subDirs   = null, files = null;
            var      hasFilter = !string.IsNullOrWhiteSpace(record.Config.Filter);

            try
            {
                if (record.Config.CleanupTarget == CleanupTarget.Directories ||
                    record.Config.CleanupTarget == CleanupTarget.All)
                {
                    subDirs = hasFilter
                        ? Directory.GetDirectories(record.Config.FullPath, record.Config.Filter)
                        : Directory.GetDirectories(record.Config.FullPath);
                }

                if (record.Config.CleanupTarget == CleanupTarget.Files ||
                    record.Config.CleanupTarget == CleanupTarget.All)
                {
                    files = hasFilter
                        ? Directory.GetFiles(record.Config.FullPath, record.Config.Filter)
                        : Directory.GetFiles(record.Config.FullPath);
                }
            }
            catch
            {
                Logger.Debug($"Не удалось получить список подпапок/файлов {record.Config.FullPath}");
                return;
            }

            var d = (DirectoryCleanupConfig)record.Config.Clone();

            d.LastCleanupTime = DateTime.Now;

            try
            {
                await ds.UpdateDirectory(d);
            }
            catch (DirectoryConfigNotFoundException)
            {
                Logger.Error(
                    $"Не удалось обновить поле LastCleanupTime конфигурации {d.Id}, скорее всего файл конфигурации был обновлен извне, и директория {d.FullPath} удалена из конф., это не помешает работе программы.");
            }
            catch (PersistenceDataStoreException exc)
            {
                Logger.Error($"Ошибка при обновлении данных: {exc}");
            }


            if ((files == null || !files.Any()) && (subDirs == null || !subDirs.Any()))
            {
                return;
            }

            if (subDirs != null)
            {
                foreach (var sub in subDirs)
                {
                    try
                    {
                        Directory.Delete(sub, true);
                    }
                    catch (Exception exc)
                    {
                        Logger.Error($"Не удалось удалить папку {sub}: {exc.Message}");
                    }
                }
            }

            if (files != null)
            {
                foreach (var file in files)
                {
                    try
                    {
                        File.Delete(file);
                    }
                    catch (Exception exc)
                    {
                        Logger.Error($"Не удалось удалить файл {file}: {exc.Message}");
                    }
                }
            }
        }
예제 #18
0
 public void Refresh(string parentPath, int level, Action<string> progress, bool isNew=false)
 {
     string fullPath = Path.Combine(parentPath, DirectoryName);
       bool exists = Directory.Exists(fullPath);
       if (exists)
       {
     if (level < 3)
       progress(fullPath);
     Children = new List<DirectoryStructureEntry>(Children.OrderBy(x => x.DirectoryName, LogicalStringComparer.Comparer));
     long size = Directory.GetFiles(fullPath).Select(file => new FileInfo(file)).Select(info => info.Length).Sum();
     foreach (var child in Children)
     {
       child.Refresh(fullPath, level+1, progress, isNew);
       size += child.CurrentSize;
     }
     foreach (var dir in Directory.GetDirectories(fullPath).Where(x => !IsLink(x)))
     {
       string dirName = Path.GetFileName(dir);
       if (!Children.Any(c => string.Compare(c.DirectoryName, dirName, true) == 0))
       {
     var child = new DirectoryStructureEntry {DirectoryName = dirName, State = DirectoryState.Added};
     try
     {
       child.Refresh(fullPath, level+1, progress, true);
       size += child.CurrentSize;
       Children.AddSorted(child, (x,y) => LogicalStringComparer.Comparer.Compare(x.DirectoryName, y.DirectoryName));
     }
     catch (IOException) { }
     catch (UnauthorizedAccessException) { }
       }
     }
     this.CurrentSize = size;
     if (isNew)
       State = DirectoryState.Added;
     else if (CurrentSize == PreviousSize)
       State = DirectoryState.Unchanged;
     else
       State = DirectoryState.Changed;
       }
       else
       {
     this.Children.Clear();
     this.CurrentSize = 0;
     this.State = DirectoryState.Deleted;
       }
 }