当前位置: 首页>>代码示例>>C#>>正文


C# DirectoryInfo.Select方法代码示例

本文整理汇总了C#中System.IO.DirectoryInfo.Select方法的典型用法代码示例。如果您正苦于以下问题:C# DirectoryInfo.Select方法的具体用法?C# DirectoryInfo.Select怎么用?C# DirectoryInfo.Select使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.IO.DirectoryInfo的用法示例。


在下文中一共展示了DirectoryInfo.Select方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: FolderContainsExclusive

            /// <summary>
            /// Determines whether the given folder contains only the given files, and no others
            /// </summary>
            /// <returns></returns>
            protected bool FolderContainsExclusive(string relFolderPath, IEnumerable<string> filenames, Anomalies anomalies = null)
            {
                var dirPath = Path.Combine(this.TargetDir, relFolderPath);
                var exists = Directory.Exists(dirPath);
                if (!exists)
                {
                    return false;
                }
                else
                {
                    var folderFiles = new DirectoryInfo(dirPath).GetFiles();

                    var filesInFolder = folderFiles.Select(f => f.Name).Except(filenames).ToList();
                    var expectedFiles = filenames.Except(folderFiles.Select(f => f.Name)).ToList();

                    if (anomalies != null)
                    {
                        anomalies.ExpectedFiles.AddRange(expectedFiles);
                        anomalies.UnexpectedFiles.AddRange(filesInFolder);
                    }

                    return !(filesInFolder.Any())
                        && !(expectedFiles.Any());
                }
            }
开发者ID:NuPattern,项目名称:NuPattern,代码行数:29,代码来源:VsixPackagingSpec.cs

示例2: CompareFiles

        private static void CompareFiles()
        {
            Console.Out.WriteLine("Comparing non-empty files between source repositories.");
            IEnumerable<FileInfo> lemanFiles = new DirectoryInfo(Directory.GetCurrentDirectory()).GetFiles("ATIRS_TO_ASSOCIATION_???.txt").Where(file => file.Length > 0);
            IEnumerable<FileInfo> archiveFiles = new DirectoryInfo(Directory.GetCurrentDirectory()).GetFiles("???archived.txt").Where(file => file.Length > 0);
            foreach (var associationId in lemanFiles.Select(file => file.Name.Substring(21, 3)).Except(archiveFiles.Select(file => file.Name.Substring(0, 3)))) { Console.Out.WriteLine(String.Format("Association {0} found in Leman but not in archives.", associationId)); }
            foreach (var associationId in archiveFiles.Select(file => file.Name.Substring(0, 3)).Except(lemanFiles.Select(file => file.Name.Substring(21, 3)))) { Console.Out.WriteLine(String.Format("Association {0} found in archives but not in Leman.", associationId)); }

            foreach (var lemanFile in lemanFiles)
            {
                string associationId = lemanFile.Name.Substring(21, 3);
                Console.Out.WriteLine("Reading files from association {0}.", associationId);
                List<string> associationFiles = new List<string>();
                using (var reader = File.OpenText(String.Format("ATIRS_TO_ASSOCIATION_{0:000}.txt", associationId)))
                {
                    string file = null;
                    while (((file = reader.ReadLine()) != null) && (file.Trim().Length > 0))
                    {
                        associationFiles.Add(file);
                    }
                }
                Console.Out.WriteLine("Reading archived files.");
                List<string> archivedFiles = new List<string>();
                using (var reader = File.OpenText(String.Format("{0:000}archived.txt", associationId)))
                {
                    string file = null;
                    while (((file = reader.ReadLine()) != null) && (file.Trim().Length > 0))
                    {
                        archivedFiles.Add(file);
                    }
                }
                Console.Out.WriteLine("Comparing.");
                var missingFiles = archivedFiles.Except(associationFiles);
                if (missingFiles.Count() > 0)
                {
                    using (var writer = File.CreateText(String.Format("{0:000}missing.txt", associationId)))
                    {
                        foreach (var file in missingFiles)
                        {
                            writer.WriteLine(file);
                            Console.Out.WriteLine(file);
                        }
                    }
                    using (var writer = File.CreateText(String.Format("Copy{0:000}Files.bat", associationId)))
                    {
                        foreach (var file in missingFiles)
                        {
                            writer.WriteLine(@"copy cxf\{0} .", file);
                        }
                    }
                }
            }
        }
开发者ID:mriceberg,项目名称:ScriptLib,代码行数:53,代码来源:Program.cs

示例3: Demo2_DemonstrateSimultaneousRenderToConsoleAndHtmlFile

        private static void Demo2_DemonstrateSimultaneousRenderToConsoleAndHtmlFile()
        {
            using (StreamWriter demo2Out = new StreamWriter("demo2Out.html"))
            {
                // First, let's build a collection of objects to render.
                var filesInCurrentDirectory =
                    new DirectoryInfo(Directory.GetCurrentDirectory()).GetFiles();

                // The anonymous type we're building has properties Name, Extension and CreationTime.
                // The resulting table will have a column for each of those properties.
                var objectsToRender =
                    filesInCurrentDirectory
                    .Select(x => new { x.Name, x.Extension, x.CreationTime });

                // Next, set up some table renderers. First, a writer that will write the
                // table to the console.
                var consoleTableWriter = new ConsoleTableWriter();

                consoleTableWriter.SetBorderCharacterSet(TextTableWriter.BasicAsciiBorderCharacterSet);

                // Now, a writer that will write HTML to an output file.
                var htmlTableWriter = new HtmlTableWriter(demo2Out);

                // Now, a single renderer which takes care of writing our single table to
                // both of the above destinations.
                var multipleTableRenderer = new MultipleTargetTableWriter(consoleTableWriter, htmlTableWriter);

                // Finally, we actually render the table
                TableRenderer.Render(objectsToRender, multipleTableRenderer);
            }

            // And launch a browser to display the generated html
            Process.Start("demo2Out.html");
        }
开发者ID:acha11,项目名称:Tabular,代码行数:34,代码来源:Program.cs

示例4: PreLoadAssembliesFromPath

 private static void PreLoadAssembliesFromPath(string p)
 {
     //Props to Andras Zoltan http://stackoverflow.com/users/157701/andras-zoltan
     // The below is from question http://stackoverflow.com/questions/3021613/how-to-pre-load-all-deployed-assemblies-for-an-appdomain
     //get all .dll files from the specified path and load the lot
     var files = new DirectoryInfo(p)
         .GetFiles("*.dll", SearchOption.AllDirectories);
     //you might not want recursion - handy for localised assemblies
     //though especially.
     AssemblyName a = null;
     var assemblies = AppDomain.CurrentDomain.GetAssemblies();
     foreach (var s in files.Select(fi => fi.FullName))
     {
         //now get the name of the assembly you've found, without loading it
         //though (assuming .Net 2+ of course).
         a = AssemblyName.GetAssemblyName(s);
         //sanity check - make sure we don't already have an assembly loaded
         //that, if this assembly name was passed to the loaded, would actually
         //be resolved as that assembly.  Might be unnecessary - but makes me
         //happy :)
         if (assemblies.Any(assembly => AssemblyName.ReferenceMatchesDefinition(a, assembly.GetName()))) continue;
         //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.
         Assembly.Load(a);
     }
 }
开发者ID:thinrichs,项目名称:ImplicitREST,代码行数:27,代码来源:DLLLoader.cs

示例5: CreateNotebooksFromDirectories

        private ImmutableArray<NotebookDto> CreateNotebooksFromDirectories(DirectoryInfo[] directories)
        {
            return directories.Select(dir => new NotebookDto
            {
                Name = GetNotebookName(dir),
                Directory = dir

            }).ToImmutableArray();
        }
开发者ID:eaardal,项目名称:delbert,代码行数:9,代码来源:NotebookActor.cs

示例6: LoadModsFromDirectoryAsync

        //#region Fields
        //int count;
        //int current;
        //#endregion Fields
        //#region Events
        //public delegate void StatusUpdateHandler(ModExtractorServiceStatusUpdateEventArgs status);
        //public event StatusUpdateHandler OnUpdateStatus = delegate { };
        //void RaiseUpdateStatus(int count, int currentIndex, string fileName)
        //{
        //    OnUpdateStatus(new ModExtractorServiceStatusUpdateEventArgs(count, currentIndex, fileName));
        //}
        //#endregion
        public List<ModData> LoadModsFromDirectoryAsync(string pathToDirectory)
        {
            List<ModData> result = new List<ModData>();

            try
            {
                var paths = new DirectoryInfo(pathToDirectory).GetFiles().Where(x => x.Extension.ToLowerInvariant() == ".zip" || x.Extension.ToLowerInvariant() == ".disabled");

                //count = paths.Count();

                //var moddetails = paths.AsParallel().Select(x => LoadModFromZip(x.FullName));

                Stopwatch watch = Stopwatch.StartNew();

                //foreach (var path in paths.Select(x => x.FullName))
                //{

                Parallel.ForEach<string>(paths.Select(x => x.FullName), (path) =>
                    {
                        try
                        {
                            result.Add(LoadModFromZip(path));
                        }
                        catch (Exception ex)
                        {
                            log.Error("Error loading '{0}'".Args(path), ex);
                        }
                    }
                );
                //}

                //foreach (string path in paths.Select(x => x.FullName))
                //{
                //    try
                //    {
                //        result.Add(LoadModFromZip(path));
                //    }
                //    catch (Exception ex)
                //    {
                //        log.Error("Error loading '{0}'".Args(path), ex);
                //    }
                //}

                watch.Stop();

                log.Info("Mods loaded in {0} sec", watch.ElapsedMilliseconds / 1000.0);

                //result.AddRange(moddetails.ToArray());
            }
            catch (Exception ex)
            {
                log.Error("Error while loading mods.", ex);
            }

            return result;
        }
开发者ID:Fox-Alpha,项目名称:ModCommander,代码行数:68,代码来源:ModExtractor.cs

示例7: Demo1_DemonstrateSimpleRenderToConsole

        private static void Demo1_DemonstrateSimpleRenderToConsole()
        {
            // First, let's build a collection of objects to render.
            var filesInCurrentDirectory =
                new DirectoryInfo(Directory.GetCurrentDirectory()).GetFiles();

            // The anonymous type we're building has properties Name, Extension and CreationTime.
            // The resulting table will have a column for each of those properties.
            var objectsToRender =
                filesInCurrentDirectory
                .Select(x => new { x.Name, x.Extension, x.CreationTime });

            // Now, we render the table to the console.
            TableRenderer.RenderToConsole(objectsToRender);
        }
开发者ID:acha11,项目名称:Tabular,代码行数:15,代码来源:Program.cs

示例8: GetPathCode

        private void GetPathCode(List<string> stocks, string dataPath)
        {
            string[] directories = Directory.GetDirectories(dataPath);
            if (directories != null && directories.Length > 0)
            {
                for (int i = 0; i < directories.Length; i++)
                {
                    GetPathCode(stocks, directories[i]);
                }
            }

            FileInfo[] files = new DirectoryInfo(dataPath).GetFiles();
            if (files != null && files.Length > 0)
            {
                stocks.AddRange(files.Select<FileInfo, string>(p => p.Name.ToLower().Replace(".day", string.Empty)));
            }
        }
开发者ID:philfanzhou,项目名称:PredictFuture,代码行数:17,代码来源:StockSource.cs

示例9: SetUp

        public void SetUp()
        {
            var pathToImagesTestSet = Path.Combine(@"D:\ReStudio\test1", @"raw\classified");
            var testsImagePathList = new DirectoryInfo(pathToImagesTestSet).GetFiles();

            _testImagesList = testsImagePathList.Select(fileInfo =>
            {
                var filenameElements = fileInfo.Name.Split('_');
                return new ImageTest
                {
                    FirstDigit = filenameElements[0],
                    SecondDigit = filenameElements[1],
                    Indice = filenameElements[2],
                    Path = fileInfo.FullName,
                    Image = new Bitmap(fileInfo.FullName)
                };
            });
        }
开发者ID:Neths,项目名称:ReStudio,代码行数:18,代码来源:EmguEngineTests.cs

示例10: Demo3_DemonstrateRenderToTextFile

        private static void Demo3_DemonstrateRenderToTextFile()
        {
            // First, let's build a collection of objects to render.
            var filesInCurrentDirectory =
                new DirectoryInfo(Directory.GetCurrentDirectory()).GetFiles();

            // The anonymous type we're building has properties Name, Extension and CreationTime.
            // The resulting table will have a column for each of those properties.
            var objectsToRender =
                filesInCurrentDirectory
                .Select(x => new { x.Name, x.Extension, x.CreationTime });

            using (StreamWriter demo3TextOut = new StreamWriter("demo3Out.txt"))
            {
                // Finally, we actually render the table
                TableRenderer.Render(objectsToRender, new TextTableWriter(demo3TextOut));
            }

            // And display the generated file
            Process.Start("demo3Out.txt");
        }
开发者ID:acha11,项目名称:Tabular,代码行数:21,代码来源:Program.cs

示例11: Flicker

        public ActionResult Flicker()
        {
            var files = new DirectoryInfo(System.Web.Hosting.HostingEnvironment.MapPath("~/videos")).GetFiles("flicker_*.mp4");

            var xml = new XDocument(
                new XElement("videos",
                    files.Select(f => new XElement("video", "/videos/" + f.Name)).ToArray()));

            var output = new StringBuilder();
            using (var writer = XmlWriter.Create(output))
            {
                xml.WriteTo(writer);
                writer.Flush();
            }

            return new ContentResult()
            {
                Content = output.ToString(),
                ContentEncoding = Encoding.UTF8,
                ContentType = "text/xml"
            };
        }
开发者ID:andrewmyhre,项目名称:andrewmyhredotcom,代码行数:22,代码来源:VideosController.cs

示例12: Content

        public ActionResult Content()
        {
            var files = new DirectoryInfo(ConfigurationManager.AppSettings["ContentVideosPath"]).GetFiles("v*.mp4");

            var xml = new XDocument(
                new XElement("videos",
                    files.Select(f => new XElement("video", "/videos/get/" + f.Name)).ToArray()));

            var output = new StringBuilder();
            using (var writer = XmlWriter.Create(output))
            {
                xml.WriteTo(writer);
                writer.Flush();
            }

            return new ContentResult()
                       {
                           Content=output.ToString(),
                           ContentEncoding = Encoding.UTF8,
                           ContentType="text/xml"
                       };
        }
开发者ID:andrewmyhre,项目名称:andrewmyhredotcom,代码行数:22,代码来源:VideosController.cs

示例13: BuildPackages

		/// <summary>
		/// 创建指定包
		/// </summary>
		/// <param name="e"></param>
		public void BuildPackages(Wrapper.RunworkEventArgs e, UpdateInfo ui)
		{
			var targetDir = AuProject.ParseFullPath(AuProject.DestinationDirectory);
			var appDir = AuProject.ParseFullPath(AuProject.ApplicationDirectory);

			if (!Directory.Exists(appDir))
				throw new ApplicationException("无效的应用程序目录");
			if (!Directory.Exists(targetDir))
			{
				try
				{
					Directory.CreateDirectory(targetDir);
				}
				catch (Exception ex)
				{
					throw new ApplicationException("无法创建目标目录", ex);
				}
			}

			e.ReportProgress(0, 0, "正在扫描文件列表...");
			FileInfo[] allfiles;

			try
			{
				allfiles = new DirectoryInfo(appDir).GetFiles("*.*", SearchOption.AllDirectories);
			}
			catch (Exception ex)
			{
				throw new ApplicationException("无法扫描来源目录", ex);
			}

			//生成映射,排除忽略列表
			e.ReportProgress(0, 0, "正在准备文件列表...");
			var projectItems = AuProject.Files.ToDictionary(s => s.Path, StringComparer.OrdinalIgnoreCase);
			var targetfiles = allfiles.Select(s => new KeyValuePair<string, FileInfo>(s.FullName.Remove(0, appDir.Length).Trim(Path.DirectorySeparatorChar), s))
				.Where(s => (!projectItems.ContainsKey(s.Key) && AuProject.DefaultUpdateMethod != UpdateMethod.Ignore) || (projectItems.ContainsKey(s.Key) && projectItems[s.Key].UpdateMethod != UpdateMethod.Ignore))
				.ToArray();

			//古典版的安装包?
			if (!AuProject.EnableIncreaseUpdate || AuProject.CreateCompatiblePackage)
			{
				var mainPkgId = GetPackageName("main") + "."+AuProject.PackageExtension;
				var file = System.IO.Path.Combine(targetDir, mainPkgId);
				Result.Add(mainPkgId, "兼容升级模式(或未开启增量更新时)的升级包文件");
				e.Progress.TaskCount = targetfiles.Length;
				CreateZip("正在生成兼容版升级包,正在压缩 {0}", file, ui.PackagePassword, e, targetfiles);

				var fileInfo = new System.IO.FileInfo(file);
				ui.PackageSize = fileInfo.Length;
				e.ReportProgress(0, 0, "正在计算包文件Hash...");
				ui.MD5 = Wrapper.ExtensionMethod.GetFileHash(file);
				ui.Package = mainPkgId;
			}
			if (!AuProject.EnableIncreaseUpdate) return;

			//生成主文件包
			e.ReportProgress(targetfiles.Length, 0, "");
			ui.Packages = new List<PackageInfo>();
			var mainFiles = targetfiles
				.Where(s => (!projectItems.ContainsKey(s.Key) && AuProject.DefaultUpdateMethod == UpdateMethod.Always) || (projectItems.ContainsKey(s.Key) && projectItems[s.Key].UpdateMethod == UpdateMethod.Always))
				.ToArray();
			if (mainFiles.Length > 0)
			{
				var mainPkgId = GetPackageName("alwaysintall") + "." + AuProject.PackageExtension;
				var pkgName = Path.Combine(targetDir, mainPkgId);
				e.Progress.TaskCount = mainFiles.Length;
				CreateZip("正在生成全局升级包,正在压缩 {0}", pkgName, ui.PackagePassword, e, mainFiles);
				Result.Add(mainPkgId, "全局升级包,包含必须更新的文件");


				var fileInfo = new System.IO.FileInfo(pkgName);
				ui.Packages.Add(new PackageInfo()
				{
					Version = "0.0.0.0",
					VerificationLevel = FileVerificationLevel.None,
					FilePath = "",
					FileSize = 0L,
					FileHash = "",
					PackageHash = Wrapper.ExtensionMethod.GetFileHash(pkgName),
					PackageName = mainPkgId,
					PackageSize = fileInfo.Length,
					Method = UpdateMethod.Always,
					Files = mainFiles.Select(s => s.Key).ToArray()
				});
			}

			//针对单个文件生成包
			e.Progress.TaskCount = targetfiles.Length;
			e.Progress.TaskProgress = 0;
			foreach (var file in targetfiles)
			{
				ProjectItem config;
				if (!projectItems.ContainsKey(file.Key))
				{
					if (AuProject.DefaultUpdateMethod == UpdateMethod.Always || AuProject.DefaultUpdateMethod == UpdateMethod.Ignore)
						continue;
//.........这里部分代码省略.........
开发者ID:shuax,项目名称:FSLib.App.SimpleUpdater,代码行数:101,代码来源:UpdatePackageBuilder.cs

示例14: GetIconPath

        private static string GetIconPath(string iconTag)
        {
            //this is a somewhat hit and miss method... get the highest resolution icon with the file name and in the folder specified.
            //TODO: improve this...

            var iconPathRegex = Regex.Match(iconTag, @"@{(.*?\..*?)_.*\?ms-resource://.*/Files/(.*)}");
            var iconPath = string.Empty;
            if (!iconPathRegex.Success) return iconPath;

            Func<string, string> getLogoPath = p =>
            {
                var expandedPath = Environment.ExpandEnvironmentVariables([email protected]"{p}");
                if (!Directory.Exists(expandedPath))
                {
                    return string.Empty;
                }

                var folderPaths = new DirectoryInfo(expandedPath).GetDirectories([email protected]"{iconPathRegex.Groups[1].Value}*");

                var imageNameWithoutExtension = Path.GetFileNameWithoutExtension(iconPathRegex.Groups[2].Value);

                if (folderPaths.Length == 0)
                    return string.Empty;

                FileInfo largestLogoPath = null;
                Image largestLogoImage = null;

                foreach (
                    var matchingLogoFiles in
                        folderPaths.Select(folderPath => folderPath?.GetFiles([email protected]"{imageNameWithoutExtension}*",
                            SearchOption.AllDirectories)))
                {
                    if (matchingLogoFiles == null) return string.Empty;
                    foreach (var logoFile in matchingLogoFiles)
                    {
                        try
                        {
                            var image = ImageUtils.LoadFileToBitmap(logoFile.FullName);
                            if (largestLogoPath == null)
                            {
                                largestLogoPath = logoFile;
                                largestLogoImage = (Image) image.Clone();
                            }
                            else
                            {
                                if (image.Width*image.Height > largestLogoImage?.Width*largestLogoImage?.Height)
                                {
                                    largestLogoPath = logoFile;
                                    largestLogoImage.Dispose();
                                    largestLogoImage = (Image) image.Clone();
                                }
                            }
                            image.Dispose();
                        }
                        catch
                        {
                            // ignore
                        }
                    }
                }
                largestLogoImage?.Dispose();
                return largestLogoPath?.FullName ?? string.Empty;
            };

            var logoPath = getLogoPath(@"%PROGRAMFILES%\WindowsApps\");
            return string.IsNullOrEmpty(logoPath) ? getLogoPath(@"%SYSTEMROOT%\SystemApps\") : logoPath;
        }
开发者ID:Jonno12345,项目名称:TileIconifier,代码行数:67,代码来源:WindowsStoreLibrary.cs

示例15: Demo6_Grids

        private static void Demo6_Grids()
        {
            // First, let's build a collection of objects to render.
            var filesInCurrentDirectory =
                new DirectoryInfo(Directory.GetCurrentDirectory()).GetFiles();

            // The anonymous type we're building has properties Name, Length, CreationTime and LastWriteTime.
            // The resulting table will have a column for each of those properties.
            var objectsToRender =
                filesInCurrentDirectory
                .Select(x => new { x.Name, x.Length, x.CreationTime, x.LastWriteTime });

            // Define the structure of the table - four columns.
            var tableStructure = TableStructure.Build()
                .Column("Name")
                .Column("Length")
                .Column("CreationTime")
                .Column("LastWriteTime")
                .Finish();

            ITableWriter tw = new MultipleTargetTableWriter(
                new ConsoleTableWriter(),
                new GridTableWriter());

            // Now, we render the table
            int threshold = 4096;
            TableRenderer.Render(objectsToRender.Where(x => x.Length > threshold), tw, tableStructure);
            TableRenderer.Render(objectsToRender.Where(x => x.Length <= threshold), tw, tableStructure);
        }
开发者ID:acha11,项目名称:Tabular,代码行数:29,代码来源:Program.cs


注:本文中的System.IO.DirectoryInfo.Select方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。