/// <summary> /// Retrieves a list of sub-directory paths from a file directory /// </summary> /// <param name="strFind">Search string to find</param> /// <param name="boolRecurse">Flag that determines whether files are retrieved recursively including files from sub-directories</param> /// <returns></returns> public DirectoryObjectList GetSubDirectories(string strFind, bool boolRecurse) { try { // Determine Search Pattern strFind = (strFind != "") ? "*" + strFind + "*" : ""; // Determine Search Option System.IO.SearchOption option = (boolRecurse == true) ? System.IO.SearchOption.AllDirectories : System.IO.SearchOption.TopDirectoryOnly; // Get File Directories List <string> listDirectories = System.IO.Directory.GetDirectories(this.FilePath, strFind, option).ToList(); // Create Directory List DirectoryObjectList directories = new DirectoryObjectList(listDirectories); return(directories); } catch (Exception ex) { // To Be Implemented: Throw Custom Exception... Console.WriteLine(ex.ToString()); return(null); } }
/// <summary> /// 找出目录下的所有子目录 /// </summary> /// <param name="rootPath">查找目录</param> /// <param name="stripDirKeys">剔除的路径关键字</param> /// <param name="sp">索目录范围</param> /// <returns></returns> public static string[] GetDirectorys(string rootPath, string[] stripDirKeys, System.IO.SearchOption sp = System.IO.SearchOption.TopDirectoryOnly) { ResultList.Clear(); string[] dirs = System.IO.Directory.GetDirectories(rootPath, "*", sp); if (dirs.Length > 0) { for (int i = 0; i < dirs.Length; i++) { string childdir = dirs[i]; childdir = childdir.Replace("\\", "/"); bool strip = false; foreach (var ext in stripDirKeys) { string dir = childdir + "/"; if (dir.Contains(ext)) { strip = true; break; } } if (strip) { continue; } ResultList.Add(childdir); } } return(ResultList.ToArray()); }
public IRuntimeContextInstance FindFiles(string dir, string mask = null, bool recursive = false) { if (mask == null) { // fix 225, 227, 228 var fObj = new FileContext(dir); if (fObj.Exists()) { return(new ArrayImpl(new[] { fObj })); } else { return(new ArrayImpl()); } } else if (File.Exists(dir)) { return(new ArrayImpl()); } System.IO.SearchOption mode = recursive ? System.IO.SearchOption.AllDirectories : System.IO.SearchOption.TopDirectoryOnly; try { var entries = System.IO.Directory.EnumerateFileSystemEntries(dir, mask, mode) .Select <string, IValue>((x) => new FileContext(x)); return(new ArrayImpl(entries)); } catch (DirectoryNotFoundException) { return(new ArrayImpl()); } }
/// <summary> /// Get a list of files based on filename-with-wildcard search criteria and file-content search criteria. /// Regular expressions are not supported (yet). /// Calls System.IO.Directory.GetFiles to get files. /// Calls System.IO.File.ReadAllText().Contains to search contents. /// Uses ToLower() to perform case-insensitive search. /// </summary> /// <param name="directoryArg">Directory to start search, such as @"C:\" or Environment.GetEnvironmentVariable("SystemRoot")</param> /// <param name="containsTextArg">Test to search for. "" will be found in any file.</param> /// <param name="ignoreCaseArg"></param> /// <param name="searchSubDirsArg"></param> /// <param name="fileWildcardsArg">Can be an array of files or a single file such as "*.ini"</param> /// <returns>a list of files (complete paths) found.</returns> static IEnumerable <string> FindInFiles( string directoryArg, string containsTextArg, bool ignoreCaseArg, System.IO.SearchOption searchSubDirsArg, params string[] fileWildcardsArg) { List <String> files = new List <string>(); // This List accumulates files found. foreach (string fileWildcard in fileWildcardsArg) { string[] xFiles = System.IO.Directory.GetFiles(directoryArg, fileWildcard, searchSubDirsArg); foreach (string x in xFiles) { if (!files.Contains(x)) // If file not already found... { // See if the file contains the search text. // Assume a null search string matches any file. // Use ToLower to perform a case-insensitive search. bool containsText = containsTextArg.Length == 0 || ignoreCaseArg? System.IO.File.ReadAllText(x).ToLower().Contains(containsTextArg.ToLower()) : System.IO.File.ReadAllText(x).Contains(containsTextArg); if (containsText) { files.Add(x); // This file is a keeper. Add it to the list. } // if } // if } // foreach file } //foreach wildcard return(files); }
static void Main(string[] args) { // 設定情報取得 _configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", true, true) .Build(); var path = GetBasePath(); var searchPatterns = GetSearchPatterns(); System.IO.SearchOption searchOption = SearchOption.AllDirectories; if (searchPatterns == null) { return; } foreach (var pattern in searchPatterns) { var directories = Directory.EnumerateDirectories(path, pattern ?? string.Empty, searchOption); foreach (var item in directories) { Directory.Delete(item, true); } } }
//找出所有文件夹全目录下的资源路径 Directory.GetFiles public string[] GetFiles(string path, System.IO.SearchOption searchOption = System.IO.SearchOption.TopDirectoryOnly) { List <string> dirs = new List <string>(); string[] files = System.IO.Directory.GetFiles(path, "*", searchOption); foreach (string file in files) { if (file.EndsWith(".meta")) { continue; } if (file.Contains(".svn")) { continue; } if (file.Contains("/Editor/")) { continue; } if (file.Contains("/Editor")) { continue; } dirs.Add(file.Replace("\\", "/")); } return(dirs.ToArray()); }
// get the files from the given path public string[] getFiles(string SourceFolder, string Filter, System.IO.SearchOption searchOption) { ArrayList alFiles = new ArrayList(); string[] MultipleFilters = Filter.Split('|'); if (IsLogicalDrive(SourceFolder)) { foreach (string d in Directory.GetDirectories(SourceFolder)) { foreach (string FileFilter in MultipleFilters) { try { alFiles.AddRange(Directory.GetFiles(d, FileFilter, searchOption)); } catch { continue; } } } } else { foreach (string FileFilter in MultipleFilters) { try { alFiles.AddRange(Directory.GetFiles(SourceFolder, FileFilter, searchOption)); } catch { continue; } } } return((string[])alFiles.ToArray(typeof(string))); }
public static string[] GetDirectories(string path, string searchPattern, System.IO.SearchOption searchOption) { searchPattern = searchPattern ?? "*"; var dirs = new List <string>(); InternalGetDirectories(path, searchPattern, searchOption, ref dirs); return(dirs.ToArray()); }
/// <summary> /// 获取目录中文件列表 /// </summary> /// <param name="dirPath">目录路径</param> /// <param name="searchPattern">查找文件的扩展名如“*.*代表所有文件;*.doc代表所有doc文件”</param> /// <param name="so">查找文件的选项,是否包含子级文件夹</param> /// <returns>文件列表</returns> public static string[] GetDirFiles(string dirPath, string searchPattern, SIO.SearchOption so) { if (!Exists(dirPath)) { throw new Util.Exception("目录不存在!"); } return(SIO.Directory.GetFiles(dirPath, searchPattern, so)); }
public static string[] GetFiles(string SourceFolder, string Filter, System.IO.SearchOption searchOption) { List <string> alFiles = new List <string>(); string[] MultipleFilters = Filter.Split('|'); foreach (string FileFilter in MultipleFilters) { alFiles.AddRange(Directory.GetFiles(SourceFolder, FileFilter, searchOption)); } return((string[])alFiles.ToArray()); }
private void SearchSubFoldersCheckBox_CheckedChanged(object sender, EventArgs e) { if (this.SearchSubFoldersCheckBox.Checked) { searchOption = System.IO.SearchOption.AllDirectories; } else { searchOption = System.IO.SearchOption.TopDirectoryOnly; } }
/// <inheritdoc/> public IEnumerable <IDirectory> GetDirectories(string searchPattern, SIO.SearchOption searchOption) { List <IDirectory> directories = new List <IDirectory>(); foreach (var currentDirectory in this.directory.GetDirectories(searchPattern, searchOption)) { directories.Add(new Directory(currentDirectory.FullName)); } return(directories); }
public string[] GetDirectories(string path, string searchPattern = null, System.IO.SearchOption searchOption = SearchOption.TopDirectoryOnly) { if (!IsLongPath(path)) { return(Directory.GetFiles(path, searchPattern)); } else { return(Win32LongPathDirectory.GetDirectories(path, searchPattern, searchOption)); } }
/// <summary> /// Folders the enumerate paths. /// </summary> /// <param name="path">The path.</param> /// <param name="searchOption">The search option.</param> /// <param name="searchPattern">The search pattern.</param> /// <returns></returns> /// <exception cref="bS.Sked2.Structure.Base.Exceptions.StorageException">Error checking folder '{path.RealPath}'. - 22</exception> /// <exception cref="StorageException">Error checking folder '{path.RealPath}'. - 22</exception> public IVirtualPath[] FolderEnumeratePaths(IVirtualPath path, System.IO.SearchOption searchOption, string searchPattern = "*") { try { return(workSpaceFileSystem.EnumeratePaths(path.RealPath, searchPattern, searchOption).Select(p => new VirtualPath(p.ToAbsolute().ToString())).ToArray()); } catch (Exception e) { throw new StorageException(logger, $"Error checking folder '{path.RealPath}'.", e, 22); } }
public static string[] getFiles(string SourceFolder, string Filter, System.IO.SearchOption searchOption) { ArrayList alFiles = new ArrayList(); string[] MultipleFilters = Filter.Split('|'); foreach (string FileFilter in MultipleFilters) { alFiles.AddRange(Directory.GetFiles(SourceFolder, "*." + FileFilter, searchOption)); } return((string[])alFiles.ToArray(typeof(string))); }
/// <summary> /// <para>Get all folder in the directory</para> /// <para>Default Level 1</para> /// </summary> public static List <DirectoryInfo> GetFolders(String path, SearchOption option = SearchOption.TopDirectoryOnly, string pattern = "*") { DirectoryInfo pathInfo = new DirectoryInfo(path); List <DirectoryInfo> folderList = new List <DirectoryInfo>(); if (pathInfo.Exists) { folderList = pathInfo.GetDirectories(pattern, option).ToList(); } return(folderList); }
/// <summary> /// 获取文件夹集合 /// </summary> /// <param name="remoteDir">远程目录</param> /// <param name="option">获取选项</param> /// <returns>文件夹集合</returns> public DirectoryInfoItem[] GetDirectories(string remoteDir, System.IO.SearchOption option = SearchOption.TopDirectoryOnly) { if (!this.ExistDirectory(remoteDir)) { return(new DirectoryInfoItem[0]); } var dirList = new List <DirectoryInfoItem>(); this.PrimitiveGetDirectories(dirList, remoteDir, option); return(dirList.ToArray()); }
private static string[] getFiles(string sourceFolder, string filters, System.IO.SearchOption searchOption) { string[] ext = filters.Split('|'); ArrayList alist = new ArrayList(); foreach (string found in ext) { alist.AddRange(Directory.GetFiles(sourceFolder, found, searchOption)); } alist.Sort(); return((string[])alist.ToArray(typeof(string))); }
public static string[] GetDirectories(string path, string searchPattern, System.IO.SearchOption searchOption) { if (TorpedoSync.Global.isWindows == false) { return(System.IO.Directory.GetDirectories(path.Replace("\\", "/"), searchPattern, searchOption)); } searchPattern = searchPattern ?? "*"; var dirs = new List <string>(); InternalGetDirectories(path, searchPattern, searchOption, ref dirs); return(dirs.ToArray()); }
private static List <string> ScanInputDirectory(string dir_path, bool recur, List <string> extentions, List <string> exclude_words) { List <string> ret_list = new List <string>(); if (dir_path.Length == 0) { return(ret_list); } DirectoryInfo dir = new DirectoryInfo(dir_path); if (!dir.Exists) { return(ret_list); } System.IO.SearchOption s_opt = SearchOption.TopDirectoryOnly; if (recur) { s_opt = SearchOption.AllDirectories; } FileInfo[] files = dir.GetFiles("*", s_opt); for (int i = 0; i < files.Length; i++) { if (extentions.Contains(files[i].Extension)) { bool needToExclude = false; for (int x = 0; x < exclude_words.Count; x++) { if (files[i].FullName.ToLower().Contains(exclude_words[x])) { needToExclude = true; } //string str1 = string.Format("{0} - {1}", files[i].FullName, exclude_words[x]); //Console.WriteLine(str1); } //string str2 = string.Format("needToExclude - {0}", needToExclude); //Console.WriteLine(str2); if (!needToExclude) { ret_list.Add(files[i].FullName); //Console.WriteLine("file added"); } } } return(ret_list); }
public static string[] GetFiles(string path, string searchPattern, System.IO.SearchOption searchOption) { if (TorpedoSync.Global.isWindows == false) { return(System.IO.Directory.GetFiles(path.Replace("\\", "/"), searchPattern, searchOption)); } searchPattern = searchPattern ?? "*"; var files = new List <string>(); var dirs = new List <string> { path }; if (searchOption == SearchOption.AllDirectories) { //Add all the subpaths dirs.AddRange(LongDirectory.GetDirectories(path, null, SearchOption.AllDirectories)); } foreach (var dir in dirs) { NativeMethods.WIN32_FIND_DATA findData; IntPtr findHandle = NativeMethods.FindFirstFile(System.IO.Path.Combine(GetWin32LongPath(dir), searchPattern), out findData); try { if (findHandle != new IntPtr(-1)) { do { if ((findData.dwFileAttributes & System.IO.FileAttributes.Directory) == 0) { string filename = System.IO.Path.Combine(dir, findData.cFileName); files.Add(GetCleanPath(filename)); } } while (NativeMethods.FindNextFile(findHandle, out findData)); NativeMethods.FindClose(findHandle); } } catch (Exception) { NativeMethods.FindClose(findHandle); throw; } } return(files.ToArray()); }
public static IEnumerable <File> GetFiles(this Dir d, string pattern, IO.SearchOption searchOption) { var prefixLen = d.ToString().Length; if (!(d.ToString().EndsWith("" + IO.Path.DirectorySeparatorChar) || d.ToString().EndsWith("" + IO.Path.AltDirectorySeparatorChar))) { prefixLen++; } // TODO: test if it also returns dirs. return(IO.Directory .GetFiles(d, pattern, searchOption) .Select(x => x.Substring(prefixLen)) .Select(x => x.File())); }
private static string[] GetFilesMulti(string sourceFolder, string filters, System.IO.SearchOption searchOption = SearchOption.TopDirectoryOnly) { try { if (!Directory.Exists(sourceFolder)) { return(new string[0]); } return(filters.Split('|').SelectMany(filter => Directory.GetFiles(sourceFolder, filter, searchOption)).ToArray()); } catch (Exception) { return(new string[0]); } }
public System.Collections.Generic.IEnumerable <string> EnumerateFiles(string path, string searchPattern, NScumm.Core.SearchOption option) { System.IO.SearchOption sysOption = System.IO.SearchOption.TopDirectoryOnly; switch (option) { case NScumm.Core.SearchOption.TopDirectoryOnly: sysOption = System.IO.SearchOption.TopDirectoryOnly; break; case NScumm.Core.SearchOption.AllDirectories: sysOption = System.IO.SearchOption.AllDirectories; break; } return(Directory.EnumerateFiles(path, searchPattern, sysOption)); }
/// <summary> /// Returns file names from given folder that comply to given filters /// </summary> /// <param name="SourceFolder">Folder with files to retrieve</param> /// <param name="Filter">Multiple file filters separated by | character</param> /// <param name="searchOption">File.IO.SearchOption, /// could be AllDirectories or TopDirectoryOnly</param> /// <returns>Array of FileInfo objects that presents collection of file names that /// meet given filter</returns> public string[] getFiles(string Folder, string Filter, System.IO.SearchOption searchOption) { // ArrayList will hold all file names ArrayList alFiles = new ArrayList(); // Create an array of filter string string[] MultipleFilters = Filter.Split('|'); // for each filter find mathing file names foreach (string FileFilter in MultipleFilters) { // add found file names to array list alFiles.AddRange(Directory.GetFiles(Folder, FileFilter, searchOption)); } // returns string array of relevant file names return((string[])alFiles.ToArray(typeof(string))); }
private void AddFilesByMask(string file, System.IO.SearchOption searchOption, SelfAwareEnumValue <ZipStorePathModeEnum> storePathMode) { // надо разделить на каталог и маску var pathEnd = file.LastIndexOfAny(new[] { '\\', '/' }); string path; string mask; IEnumerable <string> filesToAdd; if (pathEnd > 1) { path = file.Substring(0, pathEnd); var maskLen = file.Length - pathEnd - 1; if (maskLen > 0) { mask = file.Substring(pathEnd + 1, maskLen); } else { // маска была не в конце пути // 1С такое откидывает return; } // несуществующие пути или пути к файлам, вместо папок 1С откидывает if (!System.IO.Directory.Exists(path)) { return; } } else if (pathEnd == 0) { path = ""; mask = file.Substring(1); } else { path = ""; mask = file; } filesToAdd = System.IO.Directory.EnumerateFiles(path, mask, searchOption); var relativePath = System.IO.Path.GetFullPath(path); AddEnumeratedFiles(filesToAdd, relativePath, storePathMode); }
private void AddDirectory(string file, System.IO.SearchOption searchOption, SelfAwareEnumValue <ZipStorePathModeEnum> storePathMode) { var path = Path.IsPathRooted(file) ? Path.GetDirectoryName(file) : Path.GetFullPath(file); string allFilesMask; if (System.Environment.OSVersion.Platform == PlatformID.Unix || System.Environment.OSVersion.Platform == PlatformID.MacOSX) { allFilesMask = "*"; } else { allFilesMask = "*.*"; } var filesToAdd = System.IO.Directory.EnumerateFiles(file, allFilesMask, searchOption); AddEnumeratedFiles(filesToAdd, path, storePathMode); }
public static LongIO.FileInfo[] GetFiles(string path, string searchPattern, System.IO.SearchOption searchOption) { searchPattern = searchPattern ?? "*"; var files = new List <LongIO.FileInfo>(); var dirs = new List <LongIO.DirectoryInfo> { new LongIO.DirectoryInfo(path) }; if (searchOption == SearchOption.AllDirectories) { //Add all the subpaths dirs.AddRange(LongIO.Directory.GetDirectories(path, null, SearchOption.AllDirectories)); } foreach (var dir in dirs) { Win32Api.kernel32.WIN32_FIND_DATA findData; IntPtr findHandle = Win32Api.kernel32.FindFirstFile(System.IO.Path.Combine(GetWin32LongPath(dir.FullName), searchPattern), out findData); try { if (findHandle != new IntPtr(-1)) { do { if ((findData.dwFileAttributes & System.IO.FileAttributes.Directory) == 0) { string filename = System.IO.Path.Combine(dir.FullName, findData.cFileName); files.Add(new FileInfo(GetCleanPath(filename))); } } while (Win32Api.kernel32.FindNextFile(findHandle, out findData)); Win32Api.kernel32.FindClose(findHandle); } } catch (Exception) { Win32Api.kernel32.FindClose(findHandle); throw; } } return(files.ToArray()); }
/// <summary> /// Retrieves files from a file directory /// </summary> /// <param name="strFind">Search string to find</param> /// <param name="boolRecurse">Flag that determines whether files are retrieved recursively including files from sub-directories</param> /// <returns></returns> public FileObjectList GetFiles(string strFind, bool boolRecurse) { try { // Determine Search Pattern strFind = (strFind == null || strFind == "") ? "*" : strFind; strFind = (strFind.Length > 0 && strFind[0].ToString() != "*") ? "*" + strFind + "*" : strFind; // Determine Search Option System.IO.SearchOption option = (boolRecurse == true) ? System.IO.SearchOption.AllDirectories : System.IO.SearchOption.TopDirectoryOnly; // Get Directory Files List <string> listFileNames = System.IO.Directory.GetFiles(this.FilePath, strFind, option).ToList(); // Create File List FileObjectList files = new FileObjectList(listFileNames); return(files); } catch (UnauthorizedAccessException e) { // To Be Implemented: Throw Custom Exception... Console.WriteLine(e.Message); return(null); } catch (DirectoryNotFoundException e) { // To Be Implemented: Throw Custom Exception... Console.WriteLine(e.Message); return(null); } catch (IOException e) { // To Be Implemented: Throw Custom Exception... Console.WriteLine(e.Message); return(null); } catch (Exception ex) { // To Be Implemented: Throw Custom Exception... Console.WriteLine(ex.ToString()); return(null); } }
/// <summary> /// Returns file names from given folder that comply to given filters /// </summary> /// <param name="SourceFolder">Folder with files to retrieve</param> /// <param name="Filter">Multiple file filters separated by | character</param> /// <param name="searchOption">File.IO.SearchOption, /// could be AllDirectories or TopDirectoryOnly</param> /// <returns>Array of FileInfo objects that presents collection of file names that /// meet given filter</returns> private List <String> DirSearch(string SourceFolder, string Filter, System.IO.SearchOption searchOption) { // ArrayList will hold all file names List <String> alFiles = new List <String>(); // Create an array of filter string string[] MultipleFilters = Filter.Split('|'); // for each filter find mathing file names foreach (string FileFilter in MultipleFilters) { // add found file names to array list alFiles.AddRange(Directory.GetFiles(SourceFolder, FileFilter, searchOption)); } // returns string array of relevant file names return(alFiles); }
public static IEnumerable<string> EnumerateFiles(string path, string[] searchPatterns, SearchOption searchOption = SearchOption.TopDirectoryOnly) { return searchPatterns.AsParallel().SelectMany(searchPattern => Directory.EnumerateFiles(path, searchPattern, searchOption)); }
/// <summary> /// Get a list of files inside a folder that are accessible to the operator. /// </summary> /// <param name="rootPath">The root path of the folder.</param> /// <param name="patternMatch">The pattern that should be used to find the files.</param> /// <param name="searchOption">The SearchOption that should be used to find the files.</param> /// <returns>A list of files inside a folder that are accessible to the operator.</returns> private static IEnumerable<string> GetDirectoryFiles(string rootPath, string patternMatch, SearchOption searchOption) { IEnumerable<string> foundFiles = Enumerable.Empty<string>(); if (searchOption == SearchOption.AllDirectories) { try { IEnumerable<string> subDirs = Directory.EnumerateDirectories(rootPath); foreach (string dir in subDirs) { foundFiles = foundFiles.Concat(GetDirectoryFiles(dir, patternMatch, searchOption)); } } catch (UnauthorizedAccessException) { } catch (PathTooLongException) { } } try { foundFiles = foundFiles.Concat(Directory.EnumerateFiles(rootPath, patternMatch)); // Add files from the current directory } catch (UnauthorizedAccessException) { } return foundFiles; }