當前位置: 首頁>>代碼示例>>C#>>正文


C# DirectoryInfo.Where方法代碼示例

本文整理匯總了C#中System.IO.DirectoryInfo.Where方法的典型用法代碼示例。如果您正苦於以下問題:C# DirectoryInfo.Where方法的具體用法?C# DirectoryInfo.Where怎麽用?C# DirectoryInfo.Where使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在System.IO.DirectoryInfo的用法示例。


在下文中一共展示了DirectoryInfo.Where方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: Main

        static void Main(string[] args)
        {
            const string root = @"C:\Users\sp\Source\Repos\ChangeTracking\Source";
            var excluded = new[] { @"\obj", @"\bin", @"\Properties", ".vs", @"\packages" };

            Func<string, bool> isIncluded = (name) => excluded.All(e => !name.Contains(e));

            var path = new DirectoryInfo(root)
                .GetDirectories("*", SearchOption.AllDirectories)
                .Select(di => di.FullName)
                .Where(isIncluded)
                .SelectMany(Directory.GetFiles)
                .ToList();

            XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003";
            var csproj = path.Where(p => Path.GetExtension(p) == ".csproj");
            var used = csproj
                .Select(XElement.Load)
                .Elements(ns + "ItemGroup")
                .Elements(ns + "Compile")
                .Attributes("Include")
                .Select(a => a.Value)
                .Where(isIncluded)
                .Select(Path.GetFileName);

            var cs = path
                .Where(p => Path.GetExtension(p) == ".cs")
                .Select(Path.GetFileName);

            var unused = cs.Except(used);
            unused.ToList().ForEach(Console.WriteLine);
        }
開發者ID:gammja,項目名稱:UFF,代碼行數:32,代碼來源:Program.cs

示例2: ApplyDeltaPackage

        public ReleasePackage ApplyDeltaPackage(ReleasePackage basePackage, ReleasePackage deltaPackage, string outputFile)
        {
            Contract.Requires(deltaPackage != null);
            Contract.Requires(!String.IsNullOrEmpty(outputFile) && !File.Exists(outputFile));

            string workingPath;
            string deltaPath;

            using (Utility.WithTempDirectory(out deltaPath))
            using (Utility.WithTempDirectory(out workingPath))
            using (var deltaZip = new ZipFile(deltaPackage.InputPackageFile))
            using (var baseZip = new ZipFile(basePackage.InputPackageFile)) {
                deltaZip.ExtractAll(deltaPath);
                baseZip.ExtractAll(workingPath);

                var pathsVisited = new List<string>();

                var deltaPathRelativePaths = new DirectoryInfo(deltaPath).GetAllFilesRecursively()
                    .Select(x => x.FullName.Replace(deltaPath + Path.DirectorySeparatorChar, ""))
                    .ToArray();

                // Apply all of the .diff files
                deltaPathRelativePaths
                    .Where(x => x.StartsWith("lib", StringComparison.InvariantCultureIgnoreCase))
                    .ForEach(file => {
                        pathsVisited.Add(Regex.Replace(file, @".diff$", "").ToLowerInvariant());
                        applyDiffToFile(deltaPath, file, workingPath);
                    });

                // Delete all of the files that were in the old package but
                // not in the new one.
                new DirectoryInfo(workingPath).GetAllFilesRecursively()
                    .Select(x => x.FullName.Replace(workingPath + Path.DirectorySeparatorChar, "").ToLowerInvariant())
                    .Where(x => x.StartsWith("lib", StringComparison.InvariantCultureIgnoreCase) && !pathsVisited.Contains(x))
                    .ForEach(x => {
                        this.Log().Info("{0} was in old package but not in new one, deleting", x);
                        File.Delete(Path.Combine(workingPath, x));
                    });

                // Update all the files that aren't in 'lib' with the delta
                // package's versions (i.e. the nuspec file, etc etc).
                deltaPathRelativePaths
                    .Where(x => !x.StartsWith("lib", StringComparison.InvariantCultureIgnoreCase))
                    .ForEach(x => {
                        this.Log().Info("Updating metadata file: {0}", x);
                        File.Copy(Path.Combine(deltaPath, x), Path.Combine(workingPath, x), true);
                    });

                using (var zf = new ZipFile(outputFile)) {
                    zf.AddDirectory(workingPath);
                    zf.Save();
                }
            }

            return new ReleasePackage(outputFile);
        }
開發者ID:christianlang,項目名稱:Shimmer,代碼行數:56,代碼來源:DeltaPackage.cs

示例3: PreLoadAssembliesFromPath

        public void PreLoadAssembliesFromPath(string p)
        {
            //get all .dll files from the specified path and load the lot
            //you might not want recursion - handy for localised assemblies
            //though especially.
            var assemblyFiles = new DirectoryInfo(p).GetFiles("*.dll", SearchOption.AllDirectories);

            foreach (var assemblyName in assemblyFiles
                .Where(Settings.Filter)
                .Select(fi => fi.FullName)
                .Select(AssemblyName.GetAssemblyName)
                .Where(a => !AppDomain.CurrentDomain
                    .GetAssemblies()
                    .Any(assembly => AssemblyName.ReferenceMatchesDefinition(a, assembly.GetName()))))
            {
                //crucial - USE THE ASSEMBLY NAME.
                //in a web app, this assembly will automatically be bound from the
                //Asp.Net Temporary folder from where the site actually runs.
                try
                {
                    Assembly.Load(assemblyName);
                }
                catch (BadImageFormatException)
                {
                    //Debug.WriteLine(e); // TODO: just ignore this?
                }
            }
        }
開發者ID:net-industry,項目名稱:net-tools,代碼行數:28,代碼來源:AssemblyPreloader.cs

示例4: UpdateNuspecAndAssemblyInfo

		public UpdatePackagesStep UpdateNuspecAndAssemblyInfo()
		{
			var checkPackages =
				new DirectoryInfo(solutionSystemInfo.FolderPath)
					.GetFiles("AssemblyInfo.cs", SearchOption.AllDirectories)
					.Select(Packages.Parse)
					.Where(x => x != null && packagesId.Contains(x.Title))
					.GroupBy(x => x.Title)
					.ToDictionary(k => k.Key, v => new { Versions = v.Select(y => y.PackageVersion), Packages = v.Select(y => y) })
					.Where(x => x.Value.Packages.Any(y => y.HasNuget))
					.ToArray();

			var packagesWithDifferentVersions = checkPackages.Where(x => x.Value.Versions.Distinct().Count() > 1).ToArray();

			if (packagesWithDifferentVersions.Any())
			{
				ConsoleHelper.WriteLine("Packages with different versions to be fixed");

				return new UpdatePackagesStep();
			}

			var packages =
				checkPackages
					.OrderBy(x => x.Key)
					.Select(x => new PackageWithFramework(x.Key, x.Value.Versions.First(), x.Value.Packages))
					.ToArray();

			return new UpdatePackagesStep(solutionSystemInfo, buildAndRevision, packages, previousVersions);
		}
開發者ID:matteomigliore,項目名稱:HSDK,代碼行數:29,代碼來源:04.UpdateNuspecAndAssemblyInfoStep.cs

示例5: Main

        static void Main(string[] args)
        {
            var options = new Options();
            Parser.Default.ParseArguments(args , options);
            //Get all forders from the current folder
            var rootFolder = options.RootFolder == "" ? Environment.CurrentDirectory : options.RootFolder;
            var folders = new DirectoryInfo(rootFolder).GetDirectories("*.*", SearchOption.AllDirectories);
            var stats = new List<CodeFile>();

            foreach (var d in folders.Where(d => !d.Name.StartsWith(".")))
            {
                //Check if there's a .git folder here and do a git pull if that is asked for
                //if (options.GitPull) GitPull(d);

                //Check if there's a .vbp file here.
                var vbpFiles = d.GetFiles().Where(f => f.Extension.ToLower() == ".vbp");

                //Get all referenced files from the .vbp
                foreach (var vbp in vbpFiles)
                {
                    var codeFiles = GetProjectFiles(vbp);
                    //Parse each file
                    foreach (var codeFile in codeFiles)
                    {
                        var code = new CodeFile(Path.Combine(d.FullName, codeFile));
                        code.Parse();
                        stats.Add(code);
                    }
                }
            }
            if(!string.IsNullOrEmpty(options.ResultFile))
            {
                if(!File.Exists(options.ResultFile))
                {
                    File.WriteAllText(options.ResultFile, "Date\tFiles\tLines\tComments\tMethods" + Environment.NewLine);
                }
                File.AppendAllText(options.ResultFile, string.Format("{0}\t{1}\t{2}\t{3}\t{4}" + Environment.NewLine,
                DateTime.Now,
                stats.Count(),
                stats.Sum(s => s.Lines),
                stats.Sum(c => c.Comments),
                stats.Sum(m => m.Methods)
                ));
            }
            //Present the result
            if (!options.Silent)
            {
                Console.WriteLine(string.Format("Files:{0} Lines:{1} Comments:{2} Methods:{3}",
                    stats.Count(),
                    stats.Sum(s => s.Lines),
                    stats.Sum(c => c.Comments),
                    stats.Sum(m => m.Methods)
                    ));
            }
        }
開發者ID:idstam,項目名稱:vb6counter,代碼行數:55,代碼來源:Program.cs

示例6: GetFolders

        public IEnumerable<DirectoryInfo> GetFolders(string folder, string[] filter)
        {
            var path = IOHelper.MapPath("~/" + folder.TrimStart('~', '/'));
            if (filter != null && filter[0] != ".")
            {
                IEnumerable<DirectoryInfo> dirs = new DirectoryInfo(path).EnumerateDirectories();
                return dirs.Where(d => d.EnumerateFiles().Where(f => filter.Contains(f.Extension, StringComparer.OrdinalIgnoreCase)).Any());
            }

            return new DirectoryInfo(path).GetDirectories("*");
        }
開發者ID:vnbaaij,項目名稱:umbraco7-filepicker,代碼行數:11,代碼來源:FilePickerApiController.cs

示例7: Run

 public override bool Run()
 {
     if (base.Run())
     {
         DebugInfo.Add("xbl generator");
         var directoryFiles = new DirectoryInfo(this.ApiOutputDirectory).GetFiles("*.xml").Where(f => !f.Name.StartsWith("_"));
         this.ProfileFile = directoryFiles.SingleOrDefault(f => f.Name.StartsWith(string.Format(base.XmlNameFormat, "profile")));
         this.GamesFile = directoryFiles.SingleOrDefault(f => f.Name.StartsWith(string.Format(base.XmlNameFormat, "games")));
         this.GameFiles = directoryFiles.Where(f => f.Name.StartsWith(string.Format(base.XmlNameFormat, "achievements-")));
         return true;
     }
     return false;
 }
開發者ID:JamesSkemp,項目名稱:VideoGamesSpa,代碼行數:13,代碼來源:BaseXblGenerator.cs

示例8: Main

        static int Main(string[] args)
        {
            var containerBuilder = new ContainerBuilder();

            var allAssemblies = new DirectoryInfo(Environment.CurrentDirectory).GetFiles("*.dll").Select(x => Assembly.LoadFile(x.FullName));
            var assemblies = allAssemblies.Where(x => x.GetTypes().Any(t => t.IsAssignableTo<RxDemoModule>())).ToArray();

            containerBuilder.RegisterAssemblyModules(assemblies);

            var container = containerBuilder.Build();


            new MainWindow(container.Resolve<IList<IDemo>>()).ShowDialog();
            return 0;
        }
開發者ID:badamiak,項目名稱:RxDemo,代碼行數:15,代碼來源:RxDemoEntryPoint.cs

示例9: ArtBuilder

        public Tile[,] ArtBuilder(string path)
        {
            var folderPath = path.ToMapPath();
            var images = new DirectoryInfo(folderPath).GetFiles().OnlyImages();
            var config = ConfigService.Generate(folderPath);

            return images
                .Where(FilterImages)
                .Select(x => new Tile(x))
                .Aggregate(new Tile[config.Width, config.Height], (acc, tile) =>
                {
                    acc[tile.Position.X, tile.Position.Y] = tile;

                    return acc;
                });
        }
開發者ID:EricFreeman,項目名稱:Collab,代碼行數:16,代碼來源:ArtController.cs

示例10: GetEndpointName

		static string GetEndpointName(string path)
		{		
			var assemblyFiles = new DirectoryInfo(path).GetFiles("*.dll", SearchOption.AllDirectories)
				.Union(new DirectoryInfo(path).GetFiles("*.exe", SearchOption.AllDirectories));

			assemblyFiles = assemblyFiles.Where(f => !defaultAssemblyExclusions.Any(exclusion => f.Name.ToLower().StartsWith(exclusion)));			

			var results = new List<Assembly>();
			foreach (var assemblyFile in assemblyFiles)
			{
				try
				{
					var pd = new ProxyDomain();
					var assembly = pd.GetAssembly(assemblyFile.FullName);
					assembly.GetTypes();
					results.Add(assembly);
				}
				catch(Exception e)
				{
					
				}
			}


			var endPointType = ScanAssembliesForEndpoints(results).FirstOrDefault();

			if (endPointType == null)
			{
				throw new Exception(string.Format("No implementation of IConfigureThisEndpoint found in {0}", path));
			}

			//Stolen from https://github.com/NServiceBus/NServiceBus/blob/master/src/hosting/NServiceBus.Hosting.Windows/Program.cs
			var endpointConfiguration = Activator.CreateInstance(endPointType);
			var endpointName = endpointConfiguration.GetType().Namespace;

			var arr = endpointConfiguration.GetType().GetCustomAttributes(typeof(EndpointNameAttribute), false);
			if (arr.Length == 1)
				endpointName = (arr[0] as EndpointNameAttribute).Name;

			if (endpointConfiguration is INameThisEndpoint)
				endpointName = (endpointConfiguration as INameThisEndpoint).GetName();

			return endpointName;
		}
開發者ID:glennslaven,項目名稱:NserviceBus.Instrumentation,代碼行數:44,代碼來源:ServiceLoader.cs

示例11: FindSolution

 public static FileInfo FindSolution(string path)
 {
     var solutions =  new DirectoryInfo(path).GetFiles("*.sln", SearchOption.AllDirectories);
     if (solutions.Length == 0)
         throw new Exception("No solution found");
     if (solutions.Length == 1)
         return solutions.First();
     // candidates.Length > 1
     var candidatesByDepth = solutions.GroupBy(x => x.FullName.Count(ch => ch == '/')).ToList();
     var minKey2 = candidatesByDepth.Min(x => x.Key);
     var topLevelCandidates = candidatesByDepth.First(x => x.Key == minKey2);
     if (topLevelCandidates.Count() == 1)
         return topLevelCandidates.First();
     //TopLevelCandidates > 1
     var dirName = Path.GetFileName(path);
     var matchesName = solutions.Where(x => x.Name == dirName).ToList();
     if (matchesName.Count == 1)
         return matchesName.First();
     throw new Exception("Could not find solution");
 }
開發者ID:davidkron,項目名稱:DevArch,代碼行數:20,代碼來源:Program.cs

示例12: Scan

            /// <summary>
            /// Scans the given path for image files and creates a hash for every element found.
            /// </summary>
            /// <param name="path">The directory to search through.</param>
            /// <param name="checkSubdirs">Include subdirectories?</param>
            /// <param name="minDate">Ignore files older than this date.</param>
            /// <returns>Returns a dictionary with the FileInfo-object of the file as key and its hash as value.</returns>
            private Dictionary<FileInfo, ulong> Scan(string path, bool checkSubdirs, DateTime minDate)
            {
                #region Scan subdirs or not
		            SearchOption __options;
                    if (checkSubdirs) __options = SearchOption.AllDirectories;
                    else __options = SearchOption.TopDirectoryOnly;
	            #endregion
                
                //Get all files
                var __files = new DirectoryInfo(path).GetFiles(new string[] { "*.png", "*.jpg", "*.jpeg", "*.gif", "*.bmp" }, __options).ToList();

                #region Filter according to a given date
                    if (minDate != null)
                        __files = __files.Where(f => DateTime.Compare(f.LastWriteTime, minDate) >= 0).ToList();
                #endregion

                State.Max = __files.Count;

                //todo: Because this is a parallel operation, the ConcurrentDictionary class is used instead of the standard Dictionary (which is not thread-safe) 
                //Critical issue, because doing this parallel saves a huge amount of time
                //var __images = new ConcurrentDictionary<FileInfo, ulong>();
                //__files.AsParallel().ForAll((f) => 
                var __images = new Dictionary<FileInfo, ulong>();
                __files.ToList().ForEach((f) => 
                {
                    //Calling the respective overridden method to create a hash (the case where the key already exists can't happen, so it's not implemented properly)
                    __images.Add(f, GetHash(f.FullName));
                    //Update the State to give information about the current image
                    State.Current = f.Name;
                    State.Count = __files.IndexOf(f) + 1;
                });
                return __images;
            }
開發者ID:Sekagra,項目名稱:Doppelganger,代碼行數:40,代碼來源:ImageFinderBase.cs

示例13: Configure

 public void Configure(IContainer container)
 {
     var files = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory).EnumerateFiles("*.dll");
     if (files.Where(file => !IsCoreAssembly(file)).Any(TryLoadConfigurator))
         _configurator.Configure(container);
 }
開發者ID:percramer,項目名稱:pjsip4net,代碼行數:6,代碼來源:DynamicApiConfigurator.cs

示例14: FindLocalCache

 /// <summary>
 /// Find a local directory that has been created and is, thus, accessible and good where we can
 /// cache a dataset.
 /// </summary>
 /// <param name="dirCacheLocations">List of locations to look at</param>
 /// <returns></returns>
 private static DirectoryInfo FindLocalCache(DirectoryInfo[] dirCacheLocations)
 {
     return dirCacheLocations
         .Where(d => d.Exists)
         .FirstOrDefault();
 }
開發者ID:LHCAtlas,項目名稱:AtlasSSH,代碼行數:12,代碼來源:LocalMachine.cs

示例15: GetCachedChannelItemMediaSources

        public IEnumerable<MediaSourceInfo> GetCachedChannelItemMediaSources(IChannelMediaItem item)
        {
            var filenamePrefix = item.Id.ToString("N");
            var parentPath = Path.Combine(ChannelDownloadPath, item.ChannelId);

            try
            {
                var files = new DirectoryInfo(parentPath).EnumerateFiles("*", SearchOption.TopDirectoryOnly);

                if (string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase))
                {
                    files = files.Where(i => EntityResolutionHelper.IsVideoFile(i.FullName));
                }
                else
                {
                    files = files.Where(i => EntityResolutionHelper.IsAudioFile(i.FullName));
                }

                var file = files
                    .FirstOrDefault(i => i.Name.StartsWith(filenamePrefix, StringComparison.OrdinalIgnoreCase));

                if (file != null)
                {
                    var cachedItem = _libraryManager.ResolvePath(file);

                    if (cachedItem != null)
                    {
                        var hasMediaSources = _libraryManager.GetItemById(cachedItem.Id) as IHasMediaSources;

                        if (hasMediaSources != null)
                        {
                            var source = hasMediaSources.GetMediaSources(true).FirstOrDefault();

                            if (source != null)
                            {
                                source.Type = MediaSourceType.Cache;
                                return new[] { source };
                            }
                        }
                    }
                }
            }
            catch (DirectoryNotFoundException)
            {

            }

            return new List<MediaSourceInfo>();
        }
開發者ID:jmarsh0507,項目名稱:MediaBrowser,代碼行數:49,代碼來源:ChannelManager.cs


注:本文中的System.IO.DirectoryInfo.Where方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。