EnumerateFiles() public static method

public static EnumerateFiles ( string path ) : System.Collections.Generic.IEnumerable
path string
return System.Collections.Generic.IEnumerable
コード例 #1
0
        /// <summary>
        /// The process for backing up a directory index is simple:
        /// a) create hard links to all the files in the lucene directory in a temp director
        ///	   that gives us the current snapshot, and protect us from lucene's
        ///    deleting files.
        /// b) copy the hard links to the destination directory
        /// c) delete the temp directory
        /// </summary>
        public void Execute()
        {
            foreach (var file in Directory.EnumerateFiles(tempPath))
            {
                Notify("Copying " + Path.GetFileName(file));
                var fullName = new FileInfo(file).FullName;
                FileCopy(file, Path.Combine(destination, Path.GetFileName(file)), fileToSize[fullName]);
                Notify("Copied " + Path.GetFileName(file));
            }

            try
            {
                IOExtensions.DeleteDirectory(tempPath);
            }
            catch (Exception e) //cannot delete, probably because there is a file being written there
            {
                logger.WarnFormat(e, "Could not delete {0}, will delete those on startup", tempPath);

                foreach (var file in Directory.EnumerateFiles(tempPath))
                {
                    MoveFileEx(file, null, MoveFileDelayUntilReboot);
                }
                MoveFileEx(tempPath, null, MoveFileDelayUntilReboot);
            }
        }
コード例 #2
0
        /// <summary>
        /// Examine the stylesheets and collect the font families they mention.
        /// Note that the process used by ePub and bloomPub publication to
        /// determine fonts is more complicated, using the DOM in an actual browser.
        /// </summary>
        /// <returns>Enumerable of font names</returns>
        internal static IEnumerable <string> GetFontsUsed(string bookPath)
        {
            string bookHtmContent           = null;
            string defaultLangStylesContent = null;

            var result = new HashSet <string>();

            // Css for styles are contained in the actual html
            foreach (var filePath in Directory.EnumerateFiles(bookPath, "*.*").Where(f => f.EndsWith(".css") || f.EndsWith(".htm") || f.EndsWith(".html")))
            {
                var fileContents = RobustFile.ReadAllText(filePath, Encoding.UTF8);

                if (filePath.EndsWith(".htm"))
                {
                    bookHtmContent = fileContents;
                }
                else if (filePath.EndsWith("defaultLangStyles.css"))
                {
                    defaultLangStylesContent = fileContents;
                    // Delay processing defaultLangStyles to the end when we know we have the htm content.
                    continue;
                }

                HtmlDom.FindFontsUsedInCss(fileContents, result, false);
            }

            ProcessDefaultLangStyles(bookHtmContent, defaultLangStylesContent, result);

            return(result);
        }
コード例 #3
0
        public void Search_FilteredDirectoryFindedExcludeFileSystemEntry_RiseStartAndFinishEventsFindOnlyFiles()
        {
            // Arrange
            var fsv = new FileSystemVisitor();

            var isStartEventRised  = false;
            var isFinishEventRised = false;

            fsv.Start  += (sender, args) => { isStartEventRised = true; };
            fsv.Finish += (sender, args) => { isFinishEventRised = true; };
            fsv.FilteredDirectoryFinded += (sender, args) => { args.ExcludeFileSystemEntry = true; };

            // Act
            var findedEntries = fsv.Search(TestRootDirectoryName).ToArray();

            // Assert
            Assert.IsTrue(isStartEventRised);
            Assert.IsTrue(isFinishEventRised);

            var expectedEntries = DirectoryHelper.EnumerateFiles(TestRootDirectoryName, "*", SearchOption.AllDirectories).ToArray();

            Assert.IsTrue(ArrayHelper.Compare(
                              expectedEntries,
                              findedEntries,
                              StringComparison)
                          );
        }
コード例 #4
0
        private void CopyDirectory(string sourceFolder, string destinationFolder)
        {
            // check that source and destination folders exist
            if (!sourceFolder.DirectoryExists() || !destinationFolder.DirectoryExists())
            {
                return;
            }

            // copy the files over
            foreach (var file in Directory.EnumerateFiles(sourceFolder))
            {
                File.Copy(file, Path.Combine(destinationFolder, Path.GetFileName(file)), true);
            }

            // copy the directories over
            foreach (var directory in Directory.EnumerateDirectories(sourceFolder))
            {
                var destinationDirName = Path.Combine(destinationFolder, Path.GetFileName(directory));

                if (!Directory.Exists(destinationDirName))
                {
                    Directory.CreateDirectory(destinationDirName);
                }

                CopyDirectory(directory, destinationDirName);
            }
        }
コード例 #5
0
ファイル: ARealmReversed.cs プロジェクト: zaevi/SaintCoinach
        private RelationDefinition ReadDefinition()
        {
            var versionPath = Path.Combine("Definitions", "game.ver");

            if (!File.Exists(versionPath))
            {
                throw new InvalidOperationException("Definitions\\game.ver must exist.");
            }

            var version = File.ReadAllText(versionPath).Trim();
            var def     = new RelationDefinition()
            {
                Version = version
            };

            foreach (var sheetFileName in Directory.EnumerateFiles("Definitions", "*.json"))
            {
                var json     = File.ReadAllText(Path.Combine(sheetFileName), Encoding.UTF8);
                var obj      = JsonConvert.DeserializeObject <Newtonsoft.Json.Linq.JObject>(json);
                var sheetDef = SheetDefinition.FromJson(obj);
                def.SheetDefinitions.Add(sheetDef);

                if (!_GameData.SheetExists(sheetDef.Name))
                {
                    var msg = $"Defined sheet {sheetDef.Name} is missing.";
                    Debug.WriteLine(msg);
                    Console.WriteLine(msg);
                }
            }

            return(def);
        }
コード例 #6
0
        private static void GenerateIndex(string retroarchInstallPath)
        {
            Console.WriteLine("Generating system index...");
            Helpers.DeleteFilesInFolder(IndexLocation);
            var dbDir = $@"{retroarchInstallPath}\database\rdb\";

            using (var indexOutputDir = FSDirectory.Open(IndexLocation))
            {
                using (var analyzer = new StandardAnalyzer(Version.LUCENE_30))
                {
                    using (var writer = new IndexWriter(indexOutputDir, analyzer, IndexWriter.MaxFieldLength.UNLIMITED))
                    {
                        foreach (var dbPath in Directory.EnumerateFiles(dbDir, "*.rdb"))
                        {
                            var systemName = Path.GetFileNameWithoutExtension(dbPath);
                            var doc        = new Document();
                            doc.Add(new Field("Name", systemName, Field.Store.YES, Field.Index.ANALYZED));
                            writer.AddDocument(doc);
                        }

                        writer.Optimize();
                    }
                }
            }
        }
コード例 #7
0
        /// <summary>
        /// The process for backing up a directory index is simple:
        /// a) create hard links to all the files in the lucene directory in a temp director
        ///	   that gives us the current snapshot, and protect us from lucene's
        ///    deleting files.
        /// b) copy the hard links to the destination directory
        /// c) delete the temp directory
        /// </summary>
        public void Execute()
        {
            if (allowOverwrite)             // clean destination folder; we want to do this as close as possible to the actual backup operation
            {
                IOExtensions.DeleteDirectory(destination);
                Directory.CreateDirectory(destination);
            }

            foreach (var file in Directory.EnumerateFiles(tempPath))
            {
                Notify("Copying " + Path.GetFileName(file), BackupStatus.BackupMessageSeverity.Informational);
                var fullName = new FileInfo(file).FullName;
                FileCopy(file, Path.Combine(destination, Path.GetFileName(file)), fileToSize[fullName]);
                Notify("Copied " + Path.GetFileName(file), BackupStatus.BackupMessageSeverity.Informational);
            }

            try
            {
                IOExtensions.DeleteDirectory(tempPath);
            }
            catch (Exception e)             //cannot delete, probably because there is a file being written there
            {
                logger.WarnException(
                    string.Format("Could not delete {0}, will delete those on startup", tempPath),
                    e);

                foreach (var file in Directory.EnumerateFiles(tempPath))
                {
                    MoveFileEx(file, null, MoveFileDelayUntilReboot);
                }
                MoveFileEx(tempPath, null, MoveFileDelayUntilReboot);
            }
        }
コード例 #8
0
        public static string CollectionIdFromCollectionFolder(string collectionFolder)
        {
            try
            {
                var settingsFilePath = Path.Combine(collectionFolder,
                                                    Path.ChangeExtension(Path.GetFileName(collectionFolder), "bloomCollection"));
                if (!RobustFile.Exists(settingsFilePath))
                {
                    // When we're joining a TC, we extract settings in to a temp folder whose name does not
                    // match the settings file.
                    var collections = Directory.EnumerateFiles(collectionFolder,
                                                               "*.bloomCollection").ToList();
                    if (collections.Count >= 1)
                    {
                        // Hopefully this repairs things.
                        settingsFilePath = collections[0];
                    }
                    else
                    {
                        return("");
                    }
                }

                var settingsContent = RobustFile.ReadAllText(settingsFilePath, Encoding.UTF8);
                var xml             = XElement.Parse(settingsContent);
                return(ReadString(xml, "CollectionId", ""));
            }
            catch (Exception ex)
            {
                Bloom.Utils.MiscUtils.SuppressUnusedExceptionVarWarning(ex);
                return("");
            }
        }
コード例 #9
0
ファイル: AclConfiguration.cs プロジェクト: pk8est/Antd
        public void Restore()
        {
            var acls = IoDir.EnumerateFiles(_storeDir);

            foreach (var acl in acls)
            {
                Restore(acl);
            }
        }
コード例 #10
0
        private void OnExecute()
        {
            var directory  = Directory == "." ? Environment.CurrentDirectory : Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, Directory));
            var outputPath = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, Output));

            var objFolder = $"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}";
            var binFolder = $"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}";

            var files = Dir
                        .EnumerateFiles(directory, "*.cs", SearchOption.AllDirectories)
                        .Where(path => !path.Contains(binFolder) &&
                               !path.Contains(objFolder));

            if (Verbose)
            {
                Console.WriteLine("File found:");
                foreach (var f in files)
                {
                    Console.WriteLine(f);
                }
            }

            var lines = files
                        .SelectMany(file => File.ReadAllLines(file));

            var usings = lines
                         .Where(line => line.StartsWith("using"))
                         .Distinct();

            var classes = lines.Where(line => !usings.Contains(line));

            var outputDirectory = Path.GetDirectoryName(outputPath);

            System.IO.Directory.CreateDirectory(outputDirectory);

            using (var writer = File.CreateText(outputPath))
            {
                writer.WriteLine($"//Bundled {DateTime.Now}");

                foreach (var line in usings)
                {
                    writer.WriteLine(line);
                }

                writer.WriteLine();

                foreach (var line in classes)
                {
                    writer.WriteLine(line);
                }
            }

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine($"SUCCESS - Single source code file generated. {outputPath}");
            Console.ResetColor();
        }
コード例 #11
0
        public void HandleBookRename_CaseChangeOnly_WorksRight()
        {
            // Setup //
            const string originalBookName = "A new book";
            var          bookBuilder      = new BookFolderBuilder()
                                            .WithRootFolder(_collectionFolder.FolderPath)
                                            .WithTitle(originalBookName)
                                            .WithHtm("<html><body>This is just a dummy</body></html>")
                                            .Build();
            string bookFolderPath = bookBuilder.BuiltBookFolderPath;
            string htmlPath       = bookBuilder.BuiltBookHtmPath;

            TeamCollectionManager.ForceCurrentUserForTests("*****@*****.**");
            _collection.PutBook(bookFolderPath);

            var locked = _collection.AttemptLock(originalBookName);

            Assert.That(locked, Is.True, "successfully checked out book to [email protected]");

            // SUT: rename changes status in local collection folder, but not in shared repo folder
            const string newBookName       = "A New Book";
            var          newBookFolderPath = Path.Combine(_collectionFolder.FolderPath, newBookName);

            File.Move(htmlPath, Path.Combine(bookFolderPath, newBookName + ".htm"));
            // renaming directory doesn't work when names are 'the same'
            var tempPath = Path.Combine(_collectionFolder.FolderPath, "tempxxyy");

            Directory.Move(bookFolderPath, tempPath);
            Directory.Move(tempPath, newBookFolderPath);

            _collection.HandleBookRename(originalBookName, newBookName);

            _collection.PutBook(newBookFolderPath, true);

            var newRepoPath = Path.Combine(_sharedFolder.FolderPath, "Books", newBookName + ".bloom");

            // It should not have been deleted! This is a regression test for BL-10156.
            // The danger is that Windows considers the old and new names the same, so after
            // we move the file to the new name, if we go to delete the old name, we get rid of the new one.
            Assert.That(File.Exists(newRepoPath));

            // Did it get renamed?
            var matchingFiles = Directory.EnumerateFiles(Path.Combine(_sharedFolder.FolderPath, "Books"), newBookName + ".bloom").ToArray();

            Assert.That(matchingFiles[0], Is.EqualTo(Path.Combine(_sharedFolder.FolderPath, "Books", newBookName + ".bloom")));

            var newStatus  = _collection.GetLocalStatus(newBookName);
            var repoStatus = _collection.GetStatus(newBookName);

            Assert.That(newStatus, Is.Not.Null, "local status of renamed book is not null");
            Assert.That(repoStatus, Is.Not.Null, "repo status of renamed book is not null");
            Assert.That(newStatus.checksum, Is.EqualTo(repoStatus.checksum), "checksums of local and remote match after rename");
            Assert.That(newStatus.lockedBy, Is.EqualTo(null), "lockedBy of local and remote match after rename");
            Assert.That(newStatus.oldName, Is.Null, "local status has original name cleared after commit");
        }
コード例 #12
0
ファイル: AclConfiguration.cs プロジェクト: pk8est/Antd
        public Dictionary <string, string[]> GetTemplates()
        {
            var files = IoDir.EnumerateFiles(_storeDirTemplate);
            var dict  = new Dictionary <string, string[]>();

            foreach (var file in files)
            {
                dict[file] = File.ReadAllLines(file);
            }
            return(dict);
        }
コード例 #13
0
 internal static void DeleteAllThumbnails()
 {
     foreach (var file in D.EnumerateFiles(ThumbnailFolderPath, "*", SearchOption.AllDirectories))
     {
         try
         {
             F.Delete(file);
         }
         catch
         {
         }
     }
 }
コード例 #14
0
ファイル: LuceneController.cs プロジェクト: superbee66/dcForm
        private bool CreateNeeded()
        {
            DirectoryPath = RequestPaths.GetPhysicalApplicationPath("App_Data\\nosql");

            // ensure the import folder actually exists
            if (!Directory.Exists(DirectoryPath))
            {
                new DirectoryInfo(DirectoryPath)
                .mkdir()
                .Attributes = FileAttributes.NotContentIndexed | FileAttributes.Hidden;
                return(true);
            }

            return(!Directory.EnumerateFiles(DirectoryPath).Any());
        }
コード例 #15
0
        public IEnumerable <DiscoveredFile> Discover(string path, HashSet <string> existingSources)
        {
            var files = _fileTypes.AsParallel().SelectMany(pattern =>
                                                           Directory.EnumerateFiles(path, pattern, SearchOption.TopDirectoryOnly)
                                                           );
            var unprocessedFiles = files.Where(f => !existingSources.Contains(f.ToLower()))
                                   .Select(filePath => new DiscoveredFile
            {
                Name      = Path.GetFileName(filePath),
                Extension = System.IO.Path.GetExtension(filePath),
                Path      = filePath,
                Url       = filePath
            });

            return(unprocessedFiles);
        }
コード例 #16
0
    private static IEnumerable <string> EnumerateFilesInternal(
        string path,
        string searchPattern,
        bool recursively)
    {
        var localPath = Requires.NotNullOrWhiteSpace(
            path,
            nameof(path));
        var localSearchPattern = Requires.NotNullOrWhiteSpace(
            searchPattern,
            nameof(searchPattern));

        return(FSDir.EnumerateFiles(
                   localPath,
                   localSearchPattern,
                   recursively ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly));
    }
コード例 #17
0
        private static void Main()
        {
            var allVideos = Directory.EnumerateFiles(VideoPath)
                            .Where(file => file.ToLower().EndsWith(".mov")) // file.ToLower().EndsWith(".avi") ||
                            .ToList();

            foreach (var videoFile in allVideos)
            {
                HandleFile(videoFile, true, VideoDestinationPath);
            }

            var allPictures = Directory.EnumerateFiles(PicturePath)
                              .Where(file => file.ToLower().EndsWith(".jpg"))
                              .ToList();

            foreach (var picture in allPictures)
            {
                HandleFile(picture, false, PictureDestinationPath);
            }
        }
コード例 #18
0
        private void BuildFromWeiboWebPages()
        {
            var indexWriter = LuceneOperations.GetIndexWriter(WeiboConfigure.OutputPath);

            //int totalWeiboCount = 0;
            //int totalFileCount = 0;
            foreach (var filename in Directory.EnumerateFiles(WeiboConfigure.InputPath, "*.txt", SearchOption.AllDirectories))
            {
                if (Path.GetFileName(filename).StartsWith("_"))
                {
                    continue;
                }
                var parser = new WeiboParser(filename);
                foreach (var weibo in parser.GetContainedWeibo())
                {
                    Document doc = new Document();
                    doc.Add(new Field(WeiboLuceneFields.UserNickName, weibo.UserNickName, Field.Store.YES, Field.Index.ANALYZED));
                    doc.Add(new Field(WeiboLuceneFields.UserID, weibo.UserID, Field.Store.YES, Field.Index.ANALYZED));
                    doc.Add(new Field(WeiboLuceneFields.NewsArticleDescription, weibo.Content, Field.Store.YES, Field.Index.ANALYZED));
                    doc.Add(new Field(WeiboLuceneFields.DiscoveryStringTime, weibo.Time, Field.Store.YES, Field.Index.ANALYZED));
                    doc.Add(new Field(WeiboLuceneFields.Source, weibo.Source, Field.Store.YES, Field.Index.ANALYZED));
                    doc.Add(new Field(WeiboLuceneFields.UpCount, weibo.UpCount.ToString(), Field.Store.YES, Field.Index.ANALYZED));
                    doc.Add(new Field(WeiboLuceneFields.ForwardCount, weibo.ForwardCount.ToString(), Field.Store.YES, Field.Index.ANALYZED));
                    doc.Add(new Field(WeiboLuceneFields.CollectCount, weibo.CollectCount.ToString(), Field.Store.YES, Field.Index.ANALYZED));
                    doc.Add(new Field(WeiboLuceneFields.ReplyCount, weibo.ReplyCount.ToString(), Field.Store.YES, Field.Index.ANALYZED));

                    indexWriter.AddDocument(doc);
                }
                //Console.WriteLine(filename);
                //var cnt = parser.GetContainedWeibo().Count;
                //Console.WriteLine(cnt);
                //totalWeiboCount += cnt;
                //totalFileCount++;
            }

            //Console.WriteLine("Total count:" + totalWeiboCount);
            //Console.WriteLine("Total file count: " + totalFileCount);

            indexWriter.Optimize();
            indexWriter.Close();
        }
コード例 #19
0
    private static Task <IEnumerable <string> > EnumerateFilesInternalAsync(
        string path,
        string searchPattern,
        bool recursively,
        CancellationToken cancellationToken)
    {
        var localPath = Requires.NotNullOrWhiteSpace(
            path,
            nameof(path));
        var localSearchPattern = Requires.NotNullOrWhiteSpace(
            searchPattern,
            nameof(searchPattern));

        return(Work.OnThreadPoolAsync(
                   state => FSDir.EnumerateFiles(
                       state.Path,
                       state.Pattern,
                       state.Recursive),
                   (Path: localPath, Pattern: localSearchPattern, Recursive: recursively ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly),
                   cancellationToken));
    }
コード例 #20
0
        private void RemoveDirectory(string directoryFolder)
        {
            // remove all files
            foreach (var fileToBeRemoved in Directory.EnumerateFiles(directoryFolder))
            {
                fileToBeRemoved.TryHardToDelete();
            }

            // remove all subdirectories
            foreach (var folderToBeRemoved in Directory.EnumerateDirectories(directoryFolder))
            {
                RemoveDirectory(folderToBeRemoved);
            }

            try
            {
                // now try to remove the directory
                Directory.Delete(directoryFolder);
            }
            catch { }
        }
コード例 #21
0
        [DataRow("iii")]    // Missing substring
        public void Search_FilteredDirectoryFindedWithSubstringFilter_RiseEventForEachFilteredSubdirectoryInDirectory(string substring)
        {
            // Arrange
            var fsv = new FileSystemVisitor((path) => path.Contains(substring));

            var filteredDirectories = new List <string>();

            fsv.FilteredFileFinded += (sender, args) => { filteredDirectories.Add(args.Path); };

            // Act
            fsv.Search(TestRootDirectoryName).ToArray();

            // Assert
            var expectedEntries = DirectoryHelper.EnumerateFiles(TestRootDirectoryName, $"*{substring}*", SearchOption.AllDirectories).ToArray();

            Assert.IsTrue(ArrayHelper.Compare(
                              expectedEntries,
                              filteredDirectories.ToArray(),
                              StringComparison)
                          );
        }
コード例 #22
0
        public static IEnumerable <LuceneSearchModel> GetAllIndexRecords()
        {
            // validate search index
            if (!Directory.EnumerateFiles(_luceneDir).Any())
            {
                return(new List <LuceneSearchModel>());
            }

            // set up lucene searcher
            var         searcher = new IndexSearcher(_directory, false);
            IndexReader reader   = IndexReader.Open(_directory, false);
            var         docs     = new List <Document>();
            TermDocs    term     = reader.TermDocs();

            while (term.Next())
            {
                docs.Add(searcher.Doc(term.Doc));
            }
            reader.Dispose();
            searcher.Dispose();
            return(_mapLuceneToDataList(docs));
        }
コード例 #23
0
ファイル: FileSystem.cs プロジェクト: pk8est/Antd
 public static void CopyDirectory(string source, string destination)
 {
     IoDir.CreateDirectory(source);
     IoDir.CreateDirectory(destination);
     foreach (var dirPath in IoDir.EnumerateDirectories(source, "*", SearchOption.AllDirectories))
     {
         try {
             IoDir.CreateDirectory(dirPath.Replace(source, destination));
         }
         catch (Exception) {
             Bash.Execute($"mkdir -p {dirPath.Replace(source, destination)}", false);
         }
     }
     foreach (var newPath in IoDir.EnumerateFiles(source, "*", SearchOption.AllDirectories))
     {
         try {
             File.Copy(newPath, newPath.Replace(source, destination), true);
         }
         catch (Exception) {
             Bash.Execute($"cp {newPath} {newPath.Replace(source, destination)}", false);
         }
     }
 }
コード例 #24
0
        public bool DeleteEntries()
        {
            void DeleteCore(string path)
            {
                foreach (var file in D.EnumerateFiles(path))
                {
                    File.Delete(file);
                }

                foreach (var dir in D.EnumerateDirectories(path))
                {
                    DeleteCore(dir);
                    D.Delete(dir);
                }
            }

            if (!this.Exists())
            {
                return(false);
            }
            DeleteCore(this.FullName);
            return(true);
        }
コード例 #25
0
 public IEnumerable <FilePath> EnumerateFiles(string searchPattern = "*")
 => D.EnumerateFiles(this.FullName, searchPattern).Select(x => new FilePath(x, false));
コード例 #26
0
ファイル: Directory.cs プロジェクト: trungpv/Galactic
        /// <summary>
        /// Copies a directory to a new location including all files and folders beneath it.
        /// Creates a new directory if necessary.
        /// </summary>
        /// <param name="path">The path of the directory to copy.</param>
        /// <param name="newPath">The destination path to copy the directory to.</param>
        /// <param name="overwrite">Whether to overwrite any existing files in the directory being copied to.</param>
        /// <returns>True if the directory was copied. False otherwise.</returns>
        static public bool Copy(string path, string newPath, bool overwrite = false)
        {
            if (!string.IsNullOrEmpty(path) && !string.IsNullOrEmpty(newPath))
            {
                // Ensure that the paths end in a slash.
                if (!path.EndsWith(@"\"))
                {
                    // Add the slash.
                    path += @"\";
                }

                if (!newPath.EndsWith(@"\"))
                {
                    // Add the slash.
                    newPath += @"\";
                }

                // Determine if the path is a directory.
                if (SystemDirectory.Exists(path))
                {
                    // It is a directory.
                    try
                    {
                        // Check whether the directory to copy to exists.
                        if (!SystemDirectory.Exists(newPath))
                        {
                            // Clone a new directory to copy the directory into.
                            // This ensures we get the same permissions.
                            if (!Clone(path, newPath))
                            {
                                // The directory couldn't be cloned.
                                return(false);
                            }
                        }

                        // Copy the contents of subdirectories.
                        foreach (string directoryName in SystemDirectory.EnumerateDirectories(path))
                        {
                            // Get the name of the subdirectory.
                            string subDirectoryName = directoryName.Substring(path.Length);

                            // Recursively copy the directory.
                            if (!Copy(directoryName, newPath + subDirectoryName + @"\", overwrite))
                            {
                                // The directory couldn't be copied.
                                return(false);
                            }
                        }

                        // Copy any files in the directory.
                        foreach (string fileName in SystemDirectory.EnumerateFiles(path))
                        {
                            FileInfo originalFileInfo = new FileInfo(fileName);
                            if (!File.Copy(fileName, newPath, overwrite))
                            {
                                // The file couldn't be copied.
                                return(false);
                            }
                        }

                        return(true);
                    }
                    catch
                    {
                        // There was an error copying the directory or its contents.
                        return(false);
                    }
                }
            }
            // The path or newPath were null, or the path to clone did not exist.
            return(false);
        }
コード例 #27
0
ファイル: BootstrapProvider.cs プロジェクト: cvbarros/oneget
        private bool InstallNugetPackage(Package provider, Link link, string fastPath, BootstrapRequest request)
        {
            // download the nuget package
            string downloadedNupkg = request.DownloadAndValidateFile(provider._swidtag);

            if (downloadedNupkg != null)
            {
                // extracted folder
                string extractedFolder = String.Concat(FilesystemExtensions.GenerateTemporaryFileOrDirectoryNameInTempDirectory());

                try
                {
                    //unzip the file
                    ZipFile.ExtractToDirectory(downloadedNupkg, extractedFolder);

                    if (Directory.Exists(extractedFolder))
                    {
                        string versionFolder = Path.Combine(request.DestinationPath(request), provider.Name, provider.Version);
                        // tool folder is where we find things like nuget.exe
                        string toolFolder = Path.Combine(extractedFolder, "tools");
                        string libFolder  = Path.Combine(extractedFolder, "lib");

                        // create the directory version folder if not exist
                        if (!Directory.Exists(versionFolder))
                        {
                            Directory.CreateDirectory(versionFolder);
                        }

                        // copy the tools directory
                        if (Directory.Exists(toolFolder))
                        {
                            string destinationToolFolder = Path.Combine(versionFolder, "tools");

                            if (!Directory.Exists(destinationToolFolder))
                            {
                                Directory.CreateDirectory(destinationToolFolder);
                            }

                            foreach (string child in Directory.EnumerateFiles(toolFolder))
                            {
                                try
                                {
                                    // try copy and overwrite
                                    File.Copy(child, Path.Combine(destinationToolFolder, Path.GetFileName(child)), true);
                                }
                                catch (Exception e)
                                {
                                    request.Debug(e.StackTrace);
                                    if (!(e is UnauthorizedAccessException || e is IOException))
                                    {
                                        // something wrong, delete the version folder
                                        versionFolder.TryHardToDelete();
                                        return(false);
                                    }

                                    // otherwise this means the file is just being used. so just moves on to copy other files
                                }
                            }
                        }

                        // copy files from lib
                        if (Directory.Exists(libFolder))
                        {
                            // check that the lib folder has at most 1 dll
                            if (Directory.EnumerateFiles(libFolder).Count(file => String.Equals(Path.GetExtension(file), ".dll", StringComparison.OrdinalIgnoreCase)) > 1)
                            {
                                request.Warning(String.Format(CultureInfo.CurrentCulture, Resources.Messages.MoreThanOneDllExists, provider.Name));
                                return(false);
                            }

                            foreach (string child in Directory.EnumerateFiles(libFolder))
                            {
                                try
                                {
                                    File.Copy(child, Path.Combine(versionFolder, Path.GetFileName(child)), true);
                                }
                                catch (Exception e)
                                {
                                    request.Debug(e.StackTrace);
                                    if (!(e is UnauthorizedAccessException || e is IOException))
                                    {
                                        // something wrong, delete the version folder
                                        versionFolder.TryHardToDelete();
                                        return(false);
                                    }

                                    // otherwise this means the file is just being used. so just moves on to copy other files
                                }
                            }
                        }

                        // target file name is the assembly provider
                        string targetFile = Path.Combine(versionFolder, Path.GetFileName(link.Attributes[Iso19770_2.Discovery.TargetFilename]));

                        if (File.Exists(targetFile))
                        {
                            request.Verbose(Resources.Messages.InstalledPackage, provider.Name, targetFile);
                            request.YieldFromSwidtag(provider, fastPath);
                            return(true);
                        }
                    }
                }
                finally
                {
                    downloadedNupkg.TryHardToDelete();
                    extractedFolder.TryHardToDelete();
                }
            }

            return(false);
        }
コード例 #28
0
 public IEnumerable <FilePath> EnumerateAllFiles(string searchPattern = "*")
 => D.EnumerateFiles(this.FullName, searchPattern, SearchOption.AllDirectories).Select(x => new FilePath(x, false));
コード例 #29
0
 public IEnumerable <FileSystemPath> EnumerateAllEntries(string searchPattern = "*")
 => D.EnumerateDirectories(this.FullName, searchPattern, SearchOption.AllDirectories).Select(x => (FileSystemPath) new DirectoryPath(x, false))
 .Concat(D.EnumerateFiles(this.FullName, searchPattern, SearchOption.AllDirectories).Select(x => (FileSystemPath) new FilePath(x, false)));
コード例 #30
0
ファイル: Form1.cs プロジェクト: JaySmith-zz/MediaOrganizer
        public void PerformSort()
        {
            var sourceFiles = Directory.EnumerateFiles(textBoxSourceFolder.Text, textBoxSearchPattern.Text);

            foreach (var sourceFile in sourceFiles)
            {
                if (backgroundWorkerSort.CancellationPending)
                {
                    return;
                }

                var sourceFilename = new FileInfo(sourceFile).Name;
                var dateTaken      = new DateTime();

                using (var fs = new FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    var metadata = (BitmapMetadata)BitmapFrame.Create(fs).Metadata;
                    if (metadata != null)
                    {
                        DateTime.TryParse(metadata.DateTaken, out dateTaken);
                    }

                    if (dateTaken == DateTime.MinValue)
                    {
                        var fileInfo = new FileInfo(sourceFile);
                        dateTaken = fileInfo.LastWriteTime;
                    }
                }


                var targetDirectoryWithYear = Path.Combine(textBoxTargetFolder.Text, dateTaken.Year.ToString());
                if (!Directory.Exists(targetDirectoryWithYear))
                {
                    Directory.CreateDirectory(targetDirectoryWithYear);
                }

                var targetDirectoryWithYearAndMonth = string.Format("{0}", Path.Combine(targetDirectoryWithYear, dateTaken.Month.ToString().PadLeft(2, '0')));
                if (!Directory.Exists(targetDirectoryWithYearAndMonth))
                {
                    Directory.CreateDirectory(targetDirectoryWithYearAndMonth);
                }

                var imageLocation = GetImageLocation(sourceFile);
                var targetDirectoryWithYearAndMonthAndLocation = targetDirectoryWithYearAndMonth;
                if (!string.IsNullOrEmpty(imageLocation))
                {
                    targetDirectoryWithYearAndMonthAndLocation = Path.Combine(targetDirectoryWithYearAndMonth, imageLocation);
                    if (!Directory.Exists(targetDirectoryWithYearAndMonthAndLocation))
                    {
                        Directory.CreateDirectory(targetDirectoryWithYearAndMonthAndLocation);
                    }
                }

                var targetDirectoryWithYearAndMonthAndLocationAndFilename = string.Format("{0}\\{1}",
                                                                                          targetDirectoryWithYearAndMonthAndLocation, sourceFilename);

                File.Copy(sourceFile, targetDirectoryWithYearAndMonthAndLocationAndFilename, true);

                var progressText = string.Format(@"File {0} copied", sourceFilename);
                backgroundWorkerSort.ReportProgress(0, progressText);
            }
        }