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


C# DirectoryInfo.Any方法代码示例

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


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

示例1: DownloadArtifactAsync

        // This is only used by build artifact. This isn't a officially supported artifact type in RM
        public async Task DownloadArtifactAsync(IExecutionContext executionContext, IHostContext hostContext, ArtifactDefinition artifactDefinition, string dropLocation, string localFolderPath)
        {
            ArgUtil.NotNull(artifactDefinition, nameof(artifactDefinition));
            ArgUtil.NotNull(executionContext, nameof(executionContext));
            ArgUtil.NotNullOrEmpty(localFolderPath, nameof(localFolderPath));
            ArgUtil.NotNullOrEmpty(dropLocation, nameof(dropLocation));

            var trimChars = new[] { '\\', '/' };
            var relativePath = artifactDefinition.Details.RelativePath;

            // If user has specified a relative folder in the drop, change the drop location itself. 
            dropLocation = Path.Combine(dropLocation.TrimEnd(trimChars), relativePath.Trim(trimChars));

            var fileSystemManager = hostContext.CreateService<IReleaseFileSystemManager>();
            List<string> filePaths =
                new DirectoryInfo(dropLocation).EnumerateFiles("*", SearchOption.AllDirectories)
                    .Select(path => path.FullName)
                    .ToList();

            if (filePaths.Any())
            {
                foreach (var filePath in filePaths)
                {
                    var filePathRelativeToDrop = filePath.Replace(dropLocation, string.Empty).Trim(trimChars);
                    using (var fileReader = fileSystemManager.GetFileReader(filePath))
                    {
                        await fileSystemManager.WriteStreamToFile(fileReader.BaseStream, Path.Combine(localFolderPath, filePathRelativeToDrop));
                    }
                }
            }
            else
            {
                executionContext.Warning(StringUtil.Loc("RMNoArtifactsFound", relativePath));
            }
        }
开发者ID:codedebug,项目名称:vsts-agent,代码行数:36,代码来源:FileShareArtifact.cs

示例2: WritesAStreamAsync

        public async Task WritesAStreamAsync()
        {
            const string testoutputfilename = "test";
            string dir =  Config.GetDefaultDownloadDirectory();
            var files = new DirectoryInfo(dir).GetFiles().Where(n => n.Name == testoutputfilename + ".zip");
            var fileInfos = files as IList<FileInfo> ?? files.ToList();
            if (fileInfos.Any())
            {
                foreach (var file in fileInfos)
                {
                    File.Delete(file.FullName);
                }
            }
            FileInfo spyfile = new FileInfo(dir + @"\SPY_Companies.csv");

            AllDataDownloader dl = new AllDataDownloader(spyfile, null)
            {
                ZipOutput = true
            };
            await dl.WriteStreamAsync(DateTime.Now, "Test Data", dir, testoutputfilename);

            files = new DirectoryInfo(dir).GetFiles().Where(n => n.Name == testoutputfilename + ".zip");

            Assert.IsTrue(files.Any());
        }
开发者ID:bizcad,项目名称:MarketData,代码行数:25,代码来源:AllDataDownloaderTests.cs

示例3: Configure

        private void Configure(WidgetDefinition widget)
        {
            var files = new DirectoryInfo(Server.MapPath(widget.VirtualPath)).GetFiles();

            var iconFile = files.FirstOrDefault(f => f.Name.IgnoreCaseStartsWith("icon."));
            if (iconFile != null)
            {
                widget.IconUrl = UrlUtil.Combine(widget.VirtualPath, iconFile.Name);
            }

            widget.Editable = files.Any(f => f.Name.IgnoreCaseEquals("Editor.aspx"));

            var configFile = files.FirstOrDefault(f => f.Name.IgnoreCaseEquals("config.config"));
            if (configFile != null)
            {
                ApplyXmlConfig(widget, XDocument.Load(configFile.FullName).Root);
            }

            if (widget.DisplayName == null)
            {
                widget.DisplayName = new LocalizableText(String.Format("{{ Plugin={0}, Key={1} }}", widget.Plugin.Name, widget.Name));
            }
        }
开发者ID:sigcms,项目名称:Seeger,代码行数:23,代码来源:DefaultWidgetLoader.cs

示例4: btnDownload_OnClick

 protected void btnDownload_OnClick(object sender, EventArgs e)
 {
     ExportStatus(null);
     var files = new DirectoryInfo(Helper.SyncDataPath).GetFiles("*.xml");
     if (!files.Any())
     {
         DownloadStatus("No export files found for download.");
     }
     else
     {
         var xdocument = new XDocument(new XElement("uCommerceSync"));
         foreach (var fileInfo in files)
         {
             var root = XDocument.Load(fileInfo.FullName).Root;
             if (root == null)
             {
                 DownloadStatus("Export file " + fileInfo.Name + " is empty.");
                 return;
             }
             var xelement = new XElement("Entities", new XAttribute("file", fileInfo.Name), root);
             xdocument.Root.Add(xelement);
         }
         using (var memoryStream = new MemoryStream())
         {
             xdocument.Save(memoryStream, SaveOptions.None);
             var buffer = memoryStream.ToArray();
             Response.Clear();
             Response.AppendHeader("Content-Disposition",
                 "filename=uCommerceSync_" + DateTime.Now.ToString("yyyy_MM_dd_hh_mm") + ".xml");
             Response.AppendHeader("Content-Length", buffer.Length.ToString());
             Response.ContentType = "application/octet-stream";
             Response.BinaryWrite(buffer);
             Response.End();
         }
     }
     ;
 }
开发者ID:sagepath,项目名称:UCommerceSync.Sitecore,代码行数:37,代码来源:UCommerceSyncExport.aspx.cs

示例5: ParseEmlFiles

        public void ParseEmlFiles(CancellationToken token)
        {

            var emails = new DirectoryInfo(Settings.WorkingDirectory).GetFiles();

            if (emails.Any())
            {

                if (Settings.ParserMaxBatchSize > 0 && emails.Count() > Settings.ParserMaxBatchSize)
                {
                    emails = emails.Take(Settings.ParserMaxBatchSize).ToArray();
                }

                foreach (var eml in emails)
                {
                    if (token.IsCancellationRequested)
                    {
                        break;
                    }
                    var yahooHeatData = new YahooHeatData() {IsFirst = true, ServerId = Settings.ServerID};
                    var archiveFolder = Path.Combine(Settings.ArchiveDirectory, DateTime.Now.ToString("yyyyMMdd"));

                    if (!Directory.Exists(archiveFolder))
                    {
                        log.Info("Creating archive folder: " + archiveFolder);
                        Directory.CreateDirectory(archiveFolder);
                    }

                    try
                    {
                        log.Info("Parsing email " + eml.FullName);

                        var emailMessage = new MailBuilder().CreateFromEmlFile(eml.FullName);

                        yahooHeatData.RawText = emailMessage.RenderEml(true);

                        yahooHeatData.HeatTime = DateTime.Parse(emailMessage.Document.Root.Headers["x-heat-time"]);
                        yahooHeatData.heat_ip = emailMessage.Document.Root.Headers["x-heat-ip"];

                        const string fromRegex = @"\""?(?<fromname>.+)""?\s+<(?<email>.+)>";
                        var match = Regex.Match(emailMessage.Document.Root.Headers["from"], fromRegex);
                        var fromAddress = new MailAddress(match.Groups["email"].ToString(),
                            match.Groups["fromname"].ToString());

                        // FROM
                        //TODO: Where do these go?
                        //yahooHeatData.from = emailMessage.Document.Root.Headers["from"].Replace("\"", string.Empty);
                        yahooHeatData.fromnamedisplay = fromAddress.DisplayName.Replace("\"", "");
                        //yahooHeatData.FromAddress = fromAddress.Address;
                        yahooHeatData.fromemailaddress_user = fromAddress.User;
                        yahooHeatData.fromemailaddress_host = fromAddress.Host;

                        // TO
                        yahooHeatData.toemailaddress = emailMessage.Document.Root.Headers["to"];

                        var recipient = new MailAddress(emailMessage.Document.Root.Headers["to"]);
                        string recipientDomain = recipient.Host;

                        // BULK/INBOX
                        if (recipientDomain == "yahoo.com" || recipientDomain == "ymail.com" ||
                            recipientDomain == "rocketmail.com" ||
                            recipientDomain == "yahoo.co.uk" || recipientDomain == "att.net")
                        {
                            yahooHeatData.foldername =
                                string.IsNullOrEmpty(emailMessage.Document.Root.Headers["x-yahoofilteredbulk"])
                                    ? "INBOX"
                                    : "BULK";
                        }
                        else if (recipientDomain == "aol.com")
                        {
                            yahooHeatData.foldername = emailMessage.Document.Root.Headers["x-heat-folder"].ToLower() ==
                                                       "inbox"
                                ? "INBOX"
                                : "BULK";
                        }

                        yahooHeatData.subject = emailMessage.Document.Root.Headers["subject"];

                        // SENT TIME
                        yahooHeatData.DateSent = DateTime.Parse(emailMessage.Document.Root.Headers["date"]);

                        var receivedRegex = string.Empty;

                        if (recipientDomain == "yahoo.com" || recipientDomain == "ymail.com" ||
                            recipientDomain == "rocketmail.com" ||
                            recipientDomain == "yahoo.co.uk" || recipientDomain == "att.net")
                        {
                            receivedRegex =
                                @"\(EHLO\s(?<ehlodomain>[a-zA-Z0-9\-\.]+)\)\s+\((?<ehloip>(?:[0-9]{1,3}.?){4})\)\s+by\s+(?<receivedmx>[a-zA-Z0-9\.\-]+)\s+with\s+SMTP;\s+(?<receiveddate>.+)";
                        }
                        else if (recipientDomain == "aol.com")
                        {
                            receivedRegex =
                                @"\((?<ehlodomain>[a-zA-Z0-9\-\.]+)\s+\[(?<ehloip>(?:[0-9]{1,3}\.?){4})\]\)\s+by\s+(?<receivedmx>[a-zA-Z0-9\.\-]+)\s.+;\s(?<receiveddate>.+)\s\(";
                        }

                        bool matched = false;

                        foreach (var headerValue in emailMessage.Document.Root.Headers.GetValues("received"))
                        {
//.........这里部分代码省略.........
开发者ID:c0d3m0nky,项目名称:mty,代码行数:101,代码来源:ParsingService.cs

示例6: DropBox_Drop

        public void DropBox_Drop(object sender, DragEventArgs e)
        {
            dropimage.Visibility = Visibility.Hidden;

            try
            {
                if (e.Data.GetDataPresent(DataFormats.FileDrop))
                {
                    string[] DroppedFiles = (string[])e.Data.GetData(DataFormats.FileDrop);
                    string[] SupplierArray = SearchDirs.ToArray();


                    foreach (string filepath in DroppedFiles)
                    {
                        //Creating FileInfo object of path
                        FileInfo infoFile = new FileInfo(filepath);

                        string[] names = infoFile.Name.Split(new Char[] { '_', '.' });
                        string FileState;

                        if (names.Length != 5)
                        {
                            FileState = "Error";
                        }
                        else
                            switch (names[3])
                            {
                                case "C":
                                case "c":
                                    FileState = "Concept";
                                    break;
                                case "D":
                                case "d":
                                    FileState = "Design";
                                    break;
                                case "P":
                                case "p":
                                    FileState = "Pre-Released";
                                    break;
                                case "R":
                                case "r":
                                    FileState = "Released";
                                    break;
                                default:
                                    FileState = "Null";
                                    break;
                            }

                        //Creating viewer object to show info
                        ViewFile viewer = new ViewFile()
                        {
                            Extension = infoFile.Extension.ToUpper(),
                            FileSize = (infoFile.Length / 1024).ToString() + " kB",
                            PartNo = infoFile.Name.Substring(0, 7),
                            SourceLocation = filepath,
                            FileName = infoFile.Name,
                            SiteFound = false,
                            Supplier = "",
                            Version = names[1] + "." + names[2],
                            Status = FileState,
                            FolderName = ""

                        };

                        //Add the newFilename property
                        if (viewer.Extension == ".PDF")
                        {
                            viewer.NewFileName = viewer.NewFileName = $"{viewer.PartNo}D_{names[1]}_{names[2]}{viewer.Extension}";

                        }
                        else
                        {
                            viewer.NewFileName = viewer.NewFileName = $"{viewer.PartNo}_{names[1]}_{names[2]}{viewer.Extension}";
                        }

                        //Adding FileInfo object to Datagrid
                        _source.Add(viewer);

                        //Looping through every dropped file
                        string filename = viewer.PartNo;

                        //Looping through all suppliersites
                        foreach (string location in SupplierArray)
                        {
                            //Getting directories matching the filename
                            string POLib = location + @"\POLib\";
                            IEnumerable<DirectoryInfo> foundDirectories = new DirectoryInfo(POLib).EnumerateDirectories(filename);

                            bool haselements = foundDirectories.Any();
                            if (haselements)
                            {
                                if (viewer.SiteFound == false)
                                {
                                    viewer.CopySite = location;
                                    viewer.SiteFound = true;
                                    viewer.Supplier = location.Remove(0, 43);
                                    viewer.FolderName = (location + "\\POLib\\" + viewer.PartNo).Replace("\\", "/");
                                }
                                else
                                {
//.........这里部分代码省略.........
开发者ID:rogerjo,项目名称:SupplierSites,代码行数:101,代码来源:MainWindow.xaml.cs

示例7: GetPreviousDataFile

        /// <summary>
        ///     Gets the previous data file.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        /// <exception cref="System.IO.FileNotFoundException">
        ///     Attempts to locate the newest file in the list of parsed data files
        ///     returned null.
        /// </exception>
        private static FileSystemInfo GetPreviousDataFile(string name)
        {
            Debug.Assert(!string.IsNullOrWhiteSpace(name), "The file name cannot be null or empty.");

            string searchPattern = string.Format("{0}*", name);
            IEnumerable<FileSystemInfo> fileInfo = new DirectoryInfo(DataPath).GetFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly);

            if (!fileInfo.Any())
            {
                return null;
            }

            // Get the newest file in the list
            FileSystemInfo newestFile = fileInfo.OrderByDescending(f => f.CreationTime).FirstOrDefault();

            if (newestFile == null)
            {
                throw new FileNotFoundException("Attempts to locate the newest file in the list of parsed data files returned null.");
            }

            return newestFile;
        }
开发者ID:gspagel,项目名称:WeatherScraper,代码行数:31,代码来源:Program.cs

示例8: TrimOlgLogFiles

 private void TrimOlgLogFiles(string archiveLogDir, int maxMegabytes)
 {
     var files = new DirectoryInfo(archiveLogDir).GetFiles();
     if (files.Any())
     {
         var totalSize = files.Sum(info => info.Length);
         if (totalSize > ((long)maxMegabytes) * 1024L * 1024L)
         {
             var fileToDelete = files.Single(file => file.CreationTime == files.Min(info => info.CreationTime));
             fileToDelete.Delete();
             TrimOlgLogFiles(archiveLogDir, maxMegabytes);
         }
     }
 }
开发者ID:imtheman,项目名称:WurmAssistant3,代码行数:14,代码来源:LoggingManager.cs

示例9: FolderNotEmpty

            /// <summary>
            /// Determines if the given file exists in the given folder
            /// </summary>
            /// <returns></returns>
            protected bool FolderNotEmpty(string relFolderPath, string fileTypes = "*.*", Anomalies anomalies = null)
            {
                var dirPath = Path.Combine(this.TargetDir, relFolderPath);
                var exists = Directory.Exists(dirPath);
                if (!exists)
                {
                    if (anomalies != null)
                    {
                        anomalies.ExpectedFiles.Add(relFolderPath);
                    }

                    return false;
                }
                else
                {
                    var filesInFolder = new DirectoryInfo(dirPath).GetFiles(fileTypes);
                    if (!filesInFolder.Any())
                    {
                        if (anomalies != null)
                        {
                            anomalies.ExpectedFiles.Add(fileTypes);
                        }
                    }

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

示例10: GetFileName

 public string GetFileName(TeaseMedia media)
 {
     if (media.Id.StartsWith("http://") || media.Id.StartsWith("https://"))
     {
         return media.Id;
     }
     if (FullMediaDirectoryPath.StartsWith("http://") || FullMediaDirectoryPath.StartsWith("https://"))
     {
         return FullMediaDirectoryPath + media.Id;
     }
     var matchingFiles = new DirectoryInfo(FullMediaDirectoryPath).GetFiles(media.Id);
     if (matchingFiles.Any())
     {
         return matchingFiles[random.Next(matchingFiles.Length)].FullName;
     }
     return null;
 }
开发者ID:TakenagaT,项目名称:TeaseMe,代码行数:17,代码来源:Tease.cs

示例11: RenameAndSetImagesInDocument

 private void RenameAndSetImagesInDocument(LawSyncDocumentDetail lawDocument)
 {
     try
     {
         var lawDocumentId = lawDocument.DocumentControlNumber;
         var files =
             new DirectoryInfo(lawDocument.ImagesFolderPath).GetFiles(
                 string.Format("{0}{1}*", lawDocumentId,Constants.RedactItPagingNameFormat));
         if (!files.Any()) return;
         var convertedImages = new List<ConvertedImage>(); // hold the list of converted iamges. 
         foreach (var file in files)
         {
             if (String.IsNullOrEmpty(file.Name)) continue;
             var fileExtenstion = Path.GetExtension(file.Name);
             var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file.Name);
             var currentPage = fileNameWithoutExtension.Replace(lawDocumentId, "").Replace(Constants.RedactItPagingNameFormat, "");
             int pageNumber;
             if (!int.TryParse(currentPage,
                 out pageNumber))
             {
                 continue;
             }
             var imageStartingNumber = (lawDocument.ImageStartingNumber + 1) + pageNumber;
             var newFileName = string.Format("{0:D3}", imageStartingNumber) + fileExtenstion;
             var image = Path.Combine(lawDocument.ImagesFolderPath, newFileName);
             File.Move(file.FullName, image);
             var evImageRelativePath = image.Replace(_imageArchiveDirectory, string.Empty);
             evImageRelativePath = evImageRelativePath.StartsWith(@"\") ? evImageRelativePath.Remove(0, 1) : evImageRelativePath;
             convertedImages.Add(new ConvertedImage { PageNo = pageNumber, RelativePath = evImageRelativePath });
         }
         // DEVBug 169433: Page order mess up for LAW Sync reprocess. For example the first page in LAW is not the first page in EV NNV viewer,
         // e.g. the first page is 701.tif instead of 001.tif. 
         // To solve this, we need to sort the image by page Number
         var imagePaths = convertedImages.OrderBy(o => o.PageNo).Select(o => o.RelativePath).ToList();
         if (lawDocument.ProducedImages == null)
         {
             lawDocument.ProducedImages = new List<string>();
         }
         lawDocument.ProducedImages.AddRange( imagePaths );
     }
     catch (Exception ex)
     {
         //continue the image process with out rename images
         ex.Trace().Swallow();
         ReportToDirector(ex);
     }
 }
开发者ID:Rajeshbharathi,项目名称:CGN.Paralegal,代码行数:47,代码来源:LawSyncImageUpdateWorker.cs


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