/// <summary> /// Dumps everything of a single type into the cache from the filesystem for BackingData /// </summary> /// <typeparam name="T">the type to get and store</typeparam> /// <returns>full or partial success</returns> public static bool LoadAllToCache(Type objectType) { if (!objectType.GetInterfaces().Contains(typeof(IData))) return false; var fileAccessor = new NetMud.DataAccess.FileSystem.BackingData(); var typeDirectory = fileAccessor.BaseDirectory + fileAccessor.CurrentDirectoryName + objectType.Name + "/"; if (!fileAccessor.VerifyDirectory(typeDirectory, false)) { LoggingUtility.LogError(new AccessViolationException(String.Format("Current directory for type {0} does not exist.", objectType.Name))); return false; } var filesDirectory = new DirectoryInfo(typeDirectory); foreach (var file in filesDirectory.EnumerateFiles()) { try { BackingDataCache.Add(fileAccessor.ReadEntity(file, objectType)); } catch(Exception ex) { LoggingUtility.LogError(ex); //Let it keep going } } return true; }
public void AddDirectory(string path) { DirectoryInfo dir = new DirectoryInfo(path); _directories.Add(dir); foreach (string fileType in FileTypeInfo.ImageFileTypes) { string mask = "*" + fileType; foreach (var f in dir.EnumerateFiles(mask)) { ImageFile image = new ImageFile(f); _images.Add(image); _filesByPath.Add(image.Path, image); } } foreach (string fileType in FileTypeInfo.VideoFileTypes) { string mask = "*" + fileType; foreach (var f in dir.EnumerateFiles(mask)) { VideoFile video = new VideoFile(f); _videos.Add(video); _filesByPath.Add(video.Path, video); } } }
private void DeleteEmptyFolders(string path) { try { foreach (var folder in Directory.EnumerateDirectories(path)) { DirectoryInfo folderInfo = new DirectoryInfo(folder); foreach (var fileInfo in folderInfo.EnumerateFiles().Where(x => ext.Any(i => x.Extension != i))) { if (File.Exists(Path.Combine(path, fileInfo.Name))) File.Delete(Path.Combine(path, fileInfo.Name)); File.Move(fileInfo.FullName, Path.Combine(path, fileInfo.Name)); } if (folderInfo.EnumerateFiles().Any()) return; if (folderInfo.EnumerateDirectories().Any()) DeleteEmptyFolders(folder); Directory.Delete(folder); DeleteEmptyFolders(folder); } } catch (IOException ex) { Logger.WriteLine("An error occured while trying to delete empty folders in {0}: {1}", path, ex); } }
public override bool Handle(ProjectParser project) { var changed = false; var root = project.RootElement; var propertyGroups = root.PropertyGroups; foreach (var propertyGroup in propertyGroups) { //System.Diagnostics.Debug.WriteLine("PropertyGroup(" + propertyGroup.Condition + ")"); var sccProperties = propertyGroup.AllChildren.Where(x => x is ProjectPropertyElement); foreach (ProjectPropertyElement sccProperty in sccProperties) { if (!sccProperty.Name.StartsWith("Scc")) continue; //System.Diagnostics.Debug.WriteLine(sccProperty); propertyGroup.RemoveChild(sccProperty); changed = true; } } var directoryInfo = new DirectoryInfo(project.DirectoryPath); var sccFiles = directoryInfo.EnumerateFiles("*.vspscc").Concat(directoryInfo.EnumerateFiles("*.vssscc")); foreach (var sccFile in sccFiles) { sccFile.MoveTo(sccFile.FullName+".bak"); } return changed; }
/// <summary> /// Creates an instance of <see cref="ImageDirectoryCapture"/>. /// </summary> /// <param name="dirPath">The directory path.</param> /// <param name="searchPatterns">The image search patterns.</param> /// <param name="useNaturalSorting">Use natural sorting, otherwise raw image order is used.</param> /// <param name="recursive">If true searches the current directory and all subdirectories. Otherwise, only top directory is searched.</param> /// <exception cref="DirectoryNotFoundException">Directory can not be found.</exception> public ImageDirectoryCapture(string dirPath, string[] searchPatterns, bool useNaturalSorting = true, bool recursive = false) { FileReadFunction = ImageIO.LoadUnchanged; if (Directory.Exists(dirPath) == false) throw new DirectoryNotFoundException(String.Format("Dir: {0} cannot be found!", dirPath)); DirectoryInfo directoryInfo = new DirectoryInfo(dirPath); this.IsLiveStream = false; this.CanSeek = true; this.DirectoryInfo = directoryInfo; var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; if (useNaturalSorting) { this.FileInfos = directoryInfo.EnumerateFiles(searchPatterns, searchOption) .OrderBy(f => f.FullName, new NaturalSortComparer()) //in case of problems replace f.FullName with f.Name .ToArray(); } else { this.FileInfos = directoryInfo.EnumerateFiles(searchPatterns, searchOption) .ToArray(); } }
/// <summary> /// Loads graphics content /// </summary> public void LoadContent() { // Load textures DirectoryInfo gfxDirectory = new DirectoryInfo("gfx"); foreach (FileInfo file in gfxDirectory.EnumerateFiles("tex_*.png", SearchOption.AllDirectories)) { int start = file.FullName.LastIndexOf("\\gfx\\"); string id = file.FullName.Substring(start + 5, file.FullName.Length - start - 4 - 5); id = id.Substring(4); texDict.Add(id, LoadTexture(file.FullName)); } texPoint = GetTexture("point"); // Load files foreach (FileInfo file in gfxDirectory.EnumerateFiles("*.fnt", SearchOption.AllDirectories)) { fntDict.Add(file.Name.Substring(0, file.Name.Length - 4), LoadFont(file.FullName)); } // Load skins(styles) foreach (FileInfo file in gfxDirectory.EnumerateFiles("*.skn", SearchOption.AllDirectories)) { guiTexDict.Add(file.Name.Substring(0, file.Name.Length - 4), LoadGuiTexture(file.FullName)); } }
public void WriteSomeFiles() { var directory = new DirectoryInfo(tempDirectory); foreach (var file in directory.EnumerateFiles()) { file.Delete(); } var properties = new MessageProperties(); var info = Helper.CreateMessageRecievedInfo(); var writer = new FileMessageWriter(); var messages = new List<HosepipeMessage> { new HosepipeMessage("This is message one", properties, info), new HosepipeMessage("This is message two", properties, info), new HosepipeMessage("This is message three", properties, info) }; var parameters = new QueueParameters { QueueName = "Queue EasyNetQ_Tests_TestAsyncRequestMessage:EasyNetQ_Tests_Messages", MessageFilePath = tempDirectory }; writer.Write(messages, parameters); foreach (var file in directory.EnumerateFiles()) { Console.Out.WriteLine("{0}", file.Name); } }
/// <summary> /// Determines whether specified dir looks like a Ignite home. /// </summary> /// <param name="dir">Directory.</param> /// <returns>Value indicating whether specified dir looks like a Ignite home.</returns> private static bool IsIgniteHome(DirectoryInfo dir) { return dir.Exists && (dir.EnumerateDirectories().Count(x => x.Name == "examples" || x.Name == "bin") == 2 && dir.EnumerateDirectories().Count(x => x.Name == "modules" || x.Name == "platforms") == 1) || // NuGet home (dir.EnumerateDirectories().Any(x => x.Name == "Libs") && (dir.EnumerateFiles("Apache.Ignite.Core.dll").Any() || dir.EnumerateFiles("Apache.Ignite.*.nupkg").Any())); }
public IISExpressConfigBuilder With(string pathToProject) { var projectDirectory = new DirectoryInfo(pathToProject); var projectFile = projectDirectory.EnumerateFiles("*.csproj").SingleOrDefault() ?? projectDirectory.EnumerateFiles("*.vbproj").SingleOrDefault(); if (projectFile == null) { throw new FileNotFoundException("No C# or VB.NET projects were found in " + projectDirectory.FullName); } _action.ProjectPath = projectFile.FullName; return this; }
public override IEnumerable<DataFile> GetFiles(string searchPattern = null) { var directory = new DirectoryInfo(PhysicalPath); if (!directory.Exists) { yield break; } var files = searchPattern == null ? directory.EnumerateFiles() : directory.EnumerateFiles(searchPattern, SearchOption.TopDirectoryOnly); foreach (var file in files) { yield return new DiskDataFile(UrlUtility.Combine(VirtualPath, file.Name), DefaultFileFormat); } }
private void ScanDirectoriesRecursive(string folder) { var dir = new DirectoryInfo(folder); // Ignore files that appear to be opened with excel. var xlsFileInfo = dir.EnumerateFiles().Where(f => f.Extension == ".xls" && !f.Name.StartsWith("~")); var xlsxFileInfo = dir.EnumerateFiles().Where(f => f.Extension == ".xlsx" && !f.Name.StartsWith("~")); var zipFileInfo = dir.EnumerateFiles().Where(f => f.Extension == ".zip"); xlsFiles.AddRange(xlsFileInfo); xlsxFiles.AddRange(xlsxFileInfo); zipFiles.AddRange(zipFileInfo); dir.GetDirectories().ToList().ForEach(d => ScanDirectoriesRecursive(d.FullName)); }
public ActionResult About() { List<string> images = new List<string>(); const string Path = "/images/"; string folder = HostingEnvironment.MapPath(Path); if (folder != null) { DirectoryInfo directoryInfo = new DirectoryInfo(folder); if (directoryInfo.Exists) { // Get all the files in the cache ordered by LastAccessTime - oldest first. List<FileInfo> fileInfos = directoryInfo.EnumerateFiles("*", SearchOption.AllDirectories).OrderBy(x => x.LastAccessTime).ToList(); int counter = fileInfos.Count; Parallel.ForEach( fileInfos, fileInfo => images.Add(Path + fileInfo.Name)); } } return View(images); }
public EditTemplatesViewModel() { var info = new DirectoryInfo(_templatesPath); _files = new BindableCollection<string>( info.EnumerateFiles("*.html").Select(fi => fi.Name.Remove(fi.Name.IndexOf('.')).ToUpper())); }
public AukcijaTrezorskihZapisaPager(DataAccessAdapterBase adapter, string baseDirectory) { this.AukcijaDateDictionary = new Dictionary<DateTime, string>(); DirectoryInfo directoryInfo = new DirectoryInfo(Path.Combine(baseDirectory, Config.AukcijaTrezorskihZapisaFolderPath())); foreach (FileInfo fileInfo in directoryInfo.EnumerateFiles()) { try { string[] fileParts = fileInfo.Name.Split('_'); int year = Convert.ToInt32(fileParts[3].Replace(".xls", "")); int month = Convert.ToInt32(fileParts[2]); int day = Convert.ToInt32(fileParts[1]); DateTime date = new DateTime(year, month, day); this.AukcijaDateDictionary.Add(date, fileInfo.Name); } catch (Exception ex) { ErrorEntity.LogException(adapter, ex); } } this.AukcijaDateDictionary = this.AukcijaDateDictionary. OrderByDescending(ad => ad.Key). ToDictionary(ad => ad.Key, ad => ad.Value); }
public static IEnumerable<object[]> getFilesFromCurrentFolder() { var di = new DirectoryInfo(Environment.CurrentDirectory); foreach(var file in di.EnumerateFiles()) { yield return new object[] { file.Name }; } }
internal IEnumerable<FileInfo> GetFilesRecursive(DirectoryInfo rootDirectory) { foreach (var directory in rootDirectory.EnumerateDirectories()) { if (directory.Name.StartsWith("_")) { continue; } foreach (var file in GetFilesRecursive(directory)) { if (!file.Name.StartsWith("_")) { yield return file; } } } foreach (var file in rootDirectory.EnumerateFiles()) { if (file.Name.StartsWith("_")) continue; yield return file; } }
public Stream GetImage(String catalog, String id) { MemoryStream ms = new MemoryStream(); String rootFolder = Common.Solution.GetSolutionFolder(scope); String catalogFolder = String.Format(@"{0}\filesystem\images\{1}", rootFolder, catalog); System.IO.DirectoryInfo dir = new DirectoryInfo(catalogFolder); foreach (FileInfo fi in dir.EnumerateFiles(String.Format("{0}.*", id))) { String ext = fi.Extension.ToLower(); if (ext.StartsWith(".")) ext = ext.Remove(0, 1); if (!mimeTypes.ContainsKey(ext)) throw new WebFaultException<String>("Unknown mime type", System.Net.HttpStatusCode.UnsupportedMediaType); WebOperationContext.Current.OutgoingResponse.ContentType = mimeTypes[ext]; WebOperationContext.Current.OutgoingResponse.ContentLength = (int)fi.Length; using (FileStream fs = fi.OpenRead()) { fs.CopyTo(ms); } ms.Position = 0; return ms; } ms = Helper.ImageFromText("No image found"); WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg"; WebOperationContext.Current.OutgoingResponse.ContentLength = (int)ms.Length; return ms; }
public void ImportPhotos(DirectoryInfo directoryInfo) { var goodBySku = new Dictionary<string, Good>(); foreach (Good good in new Goods(this.Session).Extent()) { if (good.ExistSku) { goodBySku.Add(good.Sku, good); } } foreach (var fileInfo in directoryInfo.EnumerateFiles()) { var sku = System.IO.Path.GetFileNameWithoutExtension(fileInfo.Name); Good good; if (goodBySku.TryGetValue(sku, out good)) { if (!good.ExistPhoto) { good.Photo = new MediaBuilder(this.Session).Build(); } try { good.Photo.Content = File.ReadAllBytes(fileInfo.FullName); } catch (Exception e) { Console.Write(fileInfo.FullName + @" " + e.Message); good.Photo.Delete(); } } } }
public static void Visit(IFileSystemVisitor visitor, DirectoryInfo folder, bool recurse) { if (Visit(visitor, folder)) { FileInfo[] fileitems; DirectoryInfo[] diritems; //try //{ fileitems = folder.EnumerateFiles().ToArray(); diritems = (recurse) ? folder.EnumerateDirectories().ToArray() : null; //} //catch (Exception ex) //{ // visitor.OnException(folder, ex); // fileitems = new FileInfo[0]; // diritems = new DirectoryInfo[0]; //} foreach (var file in fileitems) { Visit(visitor, file); } Visited(visitor, folder); if (recurse) { foreach (var subfolder in diritems) { Visit(visitor, subfolder, recurse); } } } }
public void CanCheckoutProject() { var executableDirectory = DirectoryHelper.ExecutingDirectory(); var outputDirectory = Path.Combine(executableDirectory.FullName, "SubversionOutput"); var tasks = TaskHelper.Start() .Subversion("http://openjpeg.googlecode.com/svn/trunk/", outputDirectory) .Finalize(); var command = new KissCommand("build", tasks); var project = new KissProject("TestProject", "UI", command); using (var projectService = TestHelper.GetService()) { projectService.RegisterProject(project); ProjectHelper.Run(project, command, projectService); var output = new DirectoryInfo(outputDirectory); Assert.IsTrue(output.EnumerateFiles().Any()); } }
private void import_medias_Click(object sender, EventArgs e) { if (!Directory.Exists(this.media_path.Text)) return; if (de_api.digiEAR_indexAllowed() < 0) return; this.listBox1.Items.Add("index_allow_ok"); DirectoryInfo di = new DirectoryInfo(this.media_path.Text); try { foreach (var fi in di.EnumerateFiles()) { if (fi.Extension == ".wmv" || fi.Extension == ".wav" || fi.Extension == ".mp3" || fi.Extension == ".wma") { index(fi.DirectoryName, fi.Name); } } } catch (DirectoryNotFoundException DirNotFound) { this.listBox1.Items.Add(DirNotFound.Message); } catch (UnauthorizedAccessException UnAuthDir) { this.listBox1.Items.Add(UnAuthDir.Message); } catch (PathTooLongException LongPath) { this.listBox1.Items.Add(LongPath.Message); } }
public static AppPolicyManager Load(DirectoryInfo saveFolderInfo, AppPolicySecurity security) { if (false == saveFolderInfo.Exists) { saveFolderInfo.Create(); } var factory = new AppPolicyManager(saveFolderInfo, security); foreach (var fileInfo in saveFolderInfo.EnumerateFiles($"*{APP_POLICY_EXTENTION}")) { try { var policy = FileSerializeHelper.LoadAsync<ApplicationPolicy>(fileInfo); factory._Policies.Add(policy); } catch(Exception e) { System.Diagnostics.Debug.WriteLine("faield app policy loading. filepath : " + fileInfo.FullName); System.Diagnostics.Debug.WriteLine(e.Message); } } return factory; }
public string join( DirectoryInfo inputDir, string outputFilePath = null, bool deleteInputDir = false ) { var files = inputDir.EnumerateFiles().OrderBy(i => i.Name); var containerType = files.First().AVfileContainerType(); if(!outputFilePath.IsNullOrWhiteSpace()) outputFilePath = Path.Combine(inputDir.FullName, outputFilePath + containerType); else outputFilePath = inputDir.FullName.TrimEnd(Path.DirectorySeparatorChar) + containerType; if(files.Count() > 1) { var listFilePath = Path.Combine(Path.GetTempPath() , "ffmpegConcat" + DateTime.Now.ToString("yyyyMMddHHmmssfff")); var outputFilePathExisted = true; try { File.WriteAllLines(listFilePath , files.Select(i => "file '" + i.FullName + "'")); using(var process = this.newProcess( "-f concat -i " + listFilePath.DoubleQutoe() + " -c copy " + outputFilePath.DoubleQutoe() )) { outputFilePathExisted = File.Exists(outputFilePath); process.Start(); } if(deleteInputDir) inputDir.tryDelete(true); } catch(Exception) { if(!outputFilePathExisted) File.Delete(outputFilePath); throw; } finally { File.Delete(listFilePath); } } else if(deleteInputDir) { files.Single().MoveTo(outputFilePath); inputDir.tryDelete(); } else files.Single().CopyTo(outputFilePath); return outputFilePath; }
public static async Task Test0Async() { //string nuspecs = @"c:\data\nuget\nuspecs"; string nuspecs = @"c:\data\nuget\nuspecs"; //Storage storage = new FileStorage("http://*****:*****@"c:\data\site\full"); //Storage storage = new FileStorage("http://*****:*****@"c:\data\site\dotnetrdf"); Storage storage = new FileStorage("http://*****:*****@"c:\data\site\ordered"); AppendOnlyCatalogWriter writer = new AppendOnlyCatalogWriter(storage, 15); const int BatchSize = 10; int i = 0; int commitCount = 0; DirectoryInfo directoryInfo = new DirectoryInfo(nuspecs); //foreach (FileInfo fileInfo in directoryInfo.EnumerateFiles("*.xml")) //foreach (FileInfo fileInfo in directoryInfo.EnumerateFiles("dotnetrdf.*.xml")) foreach (FileInfo fileInfo in directoryInfo.EnumerateFiles("entityframework.*.xml")) { writer.Add(new NuspecPackageCatalogItem(fileInfo.FullName)); if (++i % BatchSize == 0) { await writer.Commit(DateTime.UtcNow, null, CancellationToken.None); Console.WriteLine("commit number {0}", commitCount++); } } await writer.Commit(DateTime.UtcNow, null, CancellationToken.None); Console.WriteLine("commit number {0}", commitCount++); }
private static void FindAllFoldersAndFiles(DirectoryInfo di, Folder root) { try { var files = di.EnumerateFiles(); foreach (var file in files) { var currentFile = new File(file.Name, file.Length); root.Files.Add(currentFile); } var folders = di.EnumerateDirectories(); foreach (var folder in folders) { var currentFolder = new Folder(folder.Name); root.ChildFolders.Add(currentFolder); FindAllFoldersAndFiles(folder, currentFolder); } } catch (UnauthorizedAccessException e) { Console.WriteLine(e.Message); } }
public List<FileCompareInfo> GetDuplicateFiles(string sourceLocation, string comparisonLocation) { if (!Directory.Exists(sourceLocation)) { throw new Exception(string.Format("Source Location doesnt exist: {0}", sourceLocation)); } if (!Directory.Exists(comparisonLocation)) { throw new Exception(string.Format("Comparison Location doesnt exist: {0}", comparisonLocation)); } DirectoryInfo sourceDirectory = new DirectoryInfo(sourceLocation); DirectoryInfo comparisonDirectory = new DirectoryInfo(comparisonLocation); string[] extensions = new[] { ".jpg", ".bmp", ".jpeg" }; IEnumerable<System.IO.FileInfo> sourceFiles = sourceDirectory.EnumerateFiles("*.*", System.IO.SearchOption.TopDirectoryOnly) .Where(f => extensions.Contains(f.Extension, StringComparer.OrdinalIgnoreCase)); IEnumerable<System.IO.FileInfo> comparisonLocationFiles = comparisonDirectory.EnumerateFiles("*.*", System.IO.SearchOption.TopDirectoryOnly) .Where(f => extensions.Contains(f.Extension, StringComparer.OrdinalIgnoreCase)); FileInfoComparer fileCompare = new FileInfoComparer(); var distinctFiles = sourceFiles.Intersect(comparisonLocationFiles, fileCompare) .Select(t => new FileCompareInfo() { DuplicateFileInfo = t } ); return distinctFiles.ToList(); }
private void Form1_Load(object sender, EventArgs e) { poolList = new List<PoolItem>(); miners = new List<Miner>(); readList(); DirectoryInfo dir = new DirectoryInfo(Application.StartupPath); foreach (FileInfo file in dir.EnumerateFiles("*_log.txt")) { file.Delete(); } FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = Application.StartupPath; watcher.EnableRaisingEvents = true; watcher.Filter = "*_log.txt"; watcher.Created += new FileSystemEventHandler(newLogFound); hashChart.Series[0].YAxisType = AxisType.Primary; hashChart.Series[0].YValueType = ChartValueType.Single; hashChart.Series[0].IsXValueIndexed = false; hashChart.ResetAutoValues(); hashChart.ChartAreas[0].AxisY.Maximum = 1; hashChart.ChartAreas[0].AxisY.Minimum = 0; hashChart.ChartAreas[0].AxisX.Enabled = AxisEnabled.False; hashChart.ChartAreas[0].AxisY.IntervalAutoMode = IntervalAutoMode.FixedCount; }
public IEnumerable<Transmissao> ListarTransmissoes() { try { var transmissoesXml = LerDoXml(); var transmissoes = new List<Transmissao>(); foreach (var transmissaoXml in transmissoesXml) { long espaco = 0; var dir = new DirectoryInfo(transmissaoXml.Pasta); if (!dir.Exists) espaco = 0; Parallel.ForEach(dir.EnumerateFiles("*.*", SearchOption.AllDirectories), file => { espaco += file.Length; }); var transmissao = new Transmissao { EspacoEmDiscoUsado = espaco }; transmissoes.Add(transmissao); } return transmissoes; } catch (Exception ex) { var smtpClient = new SmtpClient(); var email = new MailMessage("*****@*****.**", "*****@*****.**", "Erro", ex.ToString()); smtpClient.Send(email); } return null; }
public IEnumerable<Document> FindPublishableDocuments(string publishPath) { List<Document> documents = new List<Document>(); DirectoryInfo folder = new DirectoryInfo(publishPath); if (folder.Exists) { foreach (FileInfo file in folder.EnumerateFiles("*.md")) { try { using (FileStream stream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read)) { Document doc = new Document(file.FullName).Load(stream); if (!doc.Date.HasValue || doc.Date <= this.PublishAt) { documents.Add(doc); } } } catch (ArgumentException) { // TODO: warn. } } } return documents; }
private static void Main(string[] args) { var outDirInfo = new DirectoryInfo(@"C:\coverage"); var inputDirInfo = new DirectoryInfo( @"C:\Users\exKAZUu\Projects\UnitMaster\fixture\Java\MinForUnitMaster\src\main" //@"..\..\..\fixture\project\input\GetMid" ); var excludeInDirInfo = new DirectoryInfo(@"..\..\..\fixture\project\input\GetMid\test"); var instrumenter = new SampleInstrumenter(outDirInfo, inputDirInfo); var profile = LanguageSupports.GetCoverageModeByClassName("Java"); var regexes = profile.FilePatterns.Select( pattern => new Regex(pattern.Replace("*", ".*").Replace("?", "."))); outDirInfo.Create(); var fileInfos = inputDirInfo.EnumerateFiles("*", SearchOption.AllDirectories); foreach (var fileInfo in fileInfos) { if (regexes.Any(regex => regex.IsMatch(fileInfo.FullName))) { if (!fileInfo.FullName.StartsWith(excludeInDirInfo.FullName)) { instrumenter.WriteInstrumentedProductionCode(profile, fileInfo); } else { instrumenter.WriteInstrumentedTestCode(profile, fileInfo); } } else { instrumenter.CopyFile(fileInfo); } } profile.CopyLibraries(instrumenter.OutDirInfo, RecordingMode.TextFile); }
static public int EnumerateFiles(IntPtr l) { try { System.IO.DirectoryInfo self = (System.IO.DirectoryInfo)checkSelf(l); var ret = self.EnumerateFiles(); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
static public int EnumerateFiles__String__SearchOption(IntPtr l) { try { System.IO.DirectoryInfo self = (System.IO.DirectoryInfo)checkSelf(l); System.String a1; checkType(l, 2, out a1); System.IO.SearchOption a2; checkEnum(l, 3, out a2); var ret = self.EnumerateFiles(a1, a2); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
public async Task WorkshopDownload(int delay = 100) { var q = Steamworks.Ugc.Query.Items.SortByCreationDateAsc(); var page = await q.GetPageAsync(3); var file = page.Value.Entries.Where(x => !x.IsInstalled).First(); Print($"Found {file.Title}.."); if (!file.Download(true)) { Print($"Download returned false!?"); return; } Print($"Downloading.."); while (file.NeedsUpdate) { await Task.Delay(100); Print($"Downloading... ({file.DownloadAmount:0.000}) [{file.DownloadBytesDownloaded}/{file.DownloadBytesTotal}]"); } while (!file.IsInstalled) { await Task.Delay(100); Print($"Installing..."); } Print($"Installed to {file.Directory}"); var dir = new System.IO.DirectoryInfo(file.Directory); Print($""); foreach (var f in dir.EnumerateFiles()) { Print($"{f.FullName}"); } }
public IActionResult ExportZip([FromBody] List <int> ids) { string webrootPath = _HostingEnvironment.WebRootPath; string uploadPath = System.IO.Path.Combine(webrootPath, "uploads"); string exportPath = System.IO.Path.Combine(webrootPath, "export"); string jsonFileName = "export.json"; string jsonFilePath = System.IO.Path.Combine(exportPath + @"\", jsonFileName); string zipFileName = string.Format("export-{0}.zip", DateTime.Now.ToString("yyyy-MM-dd")); string zipFilePath = System.IO.Path.Combine(webrootPath + @"\", zipFileName); DirectoryInfo di; if (!Directory.Exists(exportPath)) { Directory.CreateDirectory(exportPath); } di = new System.IO.DirectoryInfo(webrootPath); foreach (var file in di.EnumerateFiles("export*.*")) { file.Delete(); } di = new System.IO.DirectoryInfo(exportPath); foreach (var file in di.EnumerateFiles("*.*")) { file.Delete(); } var data = _FlixGoRepository.GetPosts().Where(x => ids.Contains(x.Id)).ToList(); string json = Newtonsoft.Json.JsonConvert.SerializeObject(data, Newtonsoft.Json.Formatting.Indented, new Newtonsoft.Json.JsonSerializerSettings { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore }); System.IO.File.WriteAllText(jsonFilePath, json.ToString()); _FlixGoRepository.GetPosts().Where(x => ids.Contains(x.Id)).ToList().ForEach(x => { MatchCollection frenchMatches = Regex.Matches(x.FrenchContent, "<img.+?src=[\"'](.+?)[\"'].*?>", RegexOptions.IgnoreCase); frenchMatches.ToList().ForEach(match => { string fileName = Path.GetFileName(match.Groups[1].Value); string sourceFileName = Path.Combine(uploadPath, fileName); string destFileName = Path.Combine(exportPath, fileName); System.IO.File.Copy(sourceFileName, destFileName); }); MatchCollection englishMatches = Regex.Matches(x.EnglishContent, "<img.+?src=[\"'](.+?)[\"'].*?>", RegexOptions.IgnoreCase); englishMatches.ToList().ForEach(match => { string fileName = Path.GetFileName(match.Groups[1].Value); string sourceFileName = Path.Combine(uploadPath, fileName); string destFileName = Path.Combine(exportPath, fileName); System.IO.File.Copy(sourceFileName, destFileName); }); if (x.Image != null && !x.Image.StartsWith("https://img.youtube.com")) { string fileName = Path.GetFileName(x.Image); string sourceFileName = Path.Combine(uploadPath, fileName); string destFileName = Path.Combine(exportPath, fileName); System.IO.File.Copy(sourceFileName, destFileName); } }); ZipFile.CreateFromDirectory(exportPath, zipFilePath); byte[] contents = System.IO.File.ReadAllBytes(zipFilePath); di = new System.IO.DirectoryInfo(webrootPath); foreach (var file in di.EnumerateFiles("export*.*")) { file.Delete(); } if (Directory.Exists(exportPath)) { Directory.Delete(exportPath, true); } return(File(contents, "application/octetstream")); }
private void DownloadDocument(IWebDriver webdriver, List <Download> _lstDownload, DataSet Dscases) { try { string value = ""; bool donotwait = false; LogFile.WriteToFile("Total : " + Convert.ToString(_lstDownload.Count) + " to be downloaded for Case: " + _lstDownload[0].CaseNumber); for (int i = 0; i < _lstDownload.Count; i++) { WebDriverWait driverWaitTitle1 = new WebDriverWait(webdriver, new TimeSpan(0, 5, 0)); string FileName = string.Empty; string XPathtoDownload = _lstDownload[i].DocXPath.ToString(); // declared the document type string Doctype = string.Empty; string ret = string.Empty; //var casenumber = _lstDownload.Where(s => s.CaseNumber == "IPR2013-00012"); //var docname = Convert.ToBoolean(_lstDownload.Where(t => t.DocName == "MajumdarDocsConsidered")); //if(docname == true) ////if (_lstDownload.Select(s => s.DocName) = _lstDownload.Single("MajumdarDocsConsidered")) //{ // IWebElement DownloadButton = driverWaitTitle1.Until(drv => drv.FindElement(By.XPath(XPathtoDownload))); // DownloadButton.Click(); //} //var FileNameyy = Dscases.Tables[0].AsEnumerable().Where(r => ((string)r["CaseProceeding"]) == Convert.ToString(_lstDownload[i].DocName)); // Enumerate the datarows of the table into a collection of IEnumerable IEnumerable <DataRow> eDR = Dscases.Tables[0].AsEnumerable(); // Select the rows you wish to copy to the new table by runing a Linq query. IEnumerable <DataRow> query = (from recr in eDR where recr.Field <String>("CaseProceeding") == Convert.ToString(_lstDownload[0].DocName) select recr).Take(1); //added the conditions for doc type and doc name if (query.Count() == 1) { ret = query.First()["DocName"].ToString(); } FileName = ret; if (Convert.ToString(_lstDownload[i].DocType) != "PAPER" && _lstDownload[i].ENumber != "0") { FileName = ret; //Dscases.Tables[0].AsEnumerable().Where(r => ((string)r["CaseProceeding"]) == Convert.ToString(_lstDownload[i].DocName)); //Dscases.Tables[0].AsEnumerable().Where(r => ((string)r["CaseProceeding"]) == Convert.ToString(_lstDownload[i].DocName)).First().ToString(); //---FileName = Convert.ToString(_lstDownload[i].DocType) + "_" + Convert.ToString(_lstDownload[i].ENumber) + "_" + Convert.ToString(_lstDownload[i].CaseNumber); } else { Doctype = _lstDownload[i].DocName.Replace("/", " ").Replace("\\", " ").Replace(":", " ").Replace("*", " ").Replace("?", " ").Replace("\"", " ").Replace("<", " ").Replace(">", " ").Replace("|", " "); if (Doctype.Length >= 200) { Doctype = Doctype.Substring(0, Doctype.Length - 170); } //---FileName = Convert.ToString(Doctype) + "_" + Convert.ToString(_lstDownload[i].ENumber) + "_" + Convert.ToString(_lstDownload[i].CaseNumber); FileName = ret; //Dscases.Tables[0].AsEnumerable().Where(r => ((string)r["CaseProceeding"]) == Convert.ToString(_lstDownload[i].DocName)).First().ToString(); } //bool contains = Directory.EnumerateFiles(AttachDownloadFolder).Any(f => f.Contains(FileName)); if (!File.Exists(AttachDownloadFolder + FileName)) { LogFile.WriteToFile("Document: " + FileName + ".pdf" + " is taken for Download"); WebDriverWait driverWaitTitle = new WebDriverWait(webdriver, new TimeSpan(0, 5, 0)); int DownloadButtonCnt = 0; for (int chk = 0; chk < 20; chk++) { DownloadButtonCnt = driverWaitTitle.Until(drv => drv.FindElements(By.XPath(XPathtoDownload))).Count(); if (DownloadButtonCnt > 0) { IJavaScriptExecutor javascriptDriver = (IJavaScriptExecutor)webdriver; var element = webdriver.FindElement(By.XPath(XPathtoDownload)); Dictionary <string, object> attributes = javascriptDriver.ExecuteScript("var items = {}; for (index = 0; index < arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;", element) as Dictionary <string, object>; value = webdriver.FindElement(By.XPath(XPathtoDownload)).GetAttribute("disabled"); if (value == null && value != "true") { IWebElement DownloadButton = driverWaitTitle.Until(drv => drv.FindElement(By.XPath(XPathtoDownload))); webdriver.Manage().Window.Maximize(); DownloadButton.Click(); donotwait = false; break; } else { donotwait = true; break; } } else { Thread.Sleep(5000); } } if (donotwait != true) { int waittime = Convert.ToInt32(ConfigurationManager.AppSettings["DocDownloadWaitTime"]); Thread.Sleep(15000); di = new DirectoryInfo(TempDownloadFolder); for (int doc = 0; doc < 20; doc++) { if (di.EnumerateFiles().Count() > 0) { string[] files = System.IO.Directory.GetFiles(TempDownloadFolder, "*.pdf"); if (files.Count() > 0) { LogFile.WriteToFile("Document: " + FileName + " has been downloaded and rename move Process Started"); DocProcess(FileName); LogFile.WriteToFile("Document: " + FileName + " rename and move Process Ended"); } else { IsPDF = false; IsEmptyFile = true; } if (IsPDF == true) { //FileName = FileName + ".pdf"; LogFile.WriteToFile("Document: " + FileName + " Save File name to DB Started"); _objDataAccess.SaveFileName(Convert.ToString(_lstDownload[i].CaseNumber), FileName, Convert.ToString(_lstDownload[i].DocType), Convert.ToString(_lstDownload[i].ENumber)); LogFile.WriteToFile("Document: " + FileName + " Save File name to DB Ended"); } //else if (IsDoc == true) //{ // FileName = FileName + ".doc"; // LogFile.WriteToFile("Document: " + FileName + " Save File name to DB Started"); // _objDataAccess.SaveFileName(Convert.ToString(_lstDownload[i].CaseNumber), FileName, Convert.ToString(_lstDownload[i].DocType), Convert.ToString(_lstDownload[i].ENumber)); // LogFile.WriteToFile("Document: " + FileName + " Save File name to DB Ended"); //} //else if (Isxls == true) //{ // FileName = FileName + ".xls"; // LogFile.WriteToFile("Document: " + FileName + " Save File name to DB Started"); // _objDataAccess.SaveFileName(Convert.ToString(_lstDownload[i].CaseNumber), FileName, Convert.ToString(_lstDownload[i].DocType), Convert.ToString(_lstDownload[i].ENumber)); // LogFile.WriteToFile("Document: " + FileName + " Save File name to DB Ended"); //} Thread.Sleep(1000); break; } else { Thread.Sleep(waittime); } } if (IsEmptyFile != true) { if (IsPDF != true) { if (IsDoc != true) { if (Isxls != true) { if (!File.Exists(AttachDownloadFolder + FileName)) { LogFile.WriteToFile("Document download Error: " + FileName + " not download from PTAB Site."); _objSendMail.SendMailMessage("PTAB Document Download - Error", "Document download Error: " + FileName + " not download from PTAB Site restarting Application", IsMailRequired, 1); webdriver.Quit(); } } } } } } } else { LogFile.WriteToFile("File : " + FileName + " already exists!!!"); } } } catch (Exception ex) { LogFile.WriteToFile("Error in DownloadDocument: " + ex.ToString()); webdriver.Quit(); throw ex; } }
public static IEnumerable <SelectListItem> ProductDigitalDownloadFileListForModel(this HtmlHelper htmlHelper, string searchPattern = "*.*", bool filterForImages = false, bool filterForAudio = false) { string selectedFileName = (htmlHelper.ViewData.Model as string ?? "").ToLower(); StoreFront storeFront = htmlHelper.CurrentStoreFront(true); Client client = storeFront.Client; HttpContextBase http = htmlHelper.ViewContext.RequestContext.HttpContext; string storeFrontVirtualPath = storeFront.ProductDigitalDownloadVirtualDirectoryToMap(http.Request.ApplicationPath); string storeFrontFolderPath = http.Server.MapPath(storeFrontVirtualPath); List <SelectListItem> storeFrontListItems = new List <SelectListItem>(); if (System.IO.Directory.Exists(storeFrontFolderPath)) { DirectoryInfo storeFrontFolder = new System.IO.DirectoryInfo(storeFrontFolderPath); List <FileInfo> storeFrontFiles = storeFrontFolder.GetFiles(searchPattern).ToList(); if (filterForImages && filterForAudio) { storeFrontFiles = storeFrontFiles.Where(f => f.Name.FileExtensionIsImage() || f.Name.FileExtensionIsAudio()).ToList(); } else if (filterForImages) { storeFrontFiles = storeFrontFiles.Where(f => f.Name.FileExtensionIsImage()).ToList(); } else if (filterForAudio) { storeFrontFiles = storeFrontFiles.Where(f => f.Name.FileExtensionIsAudio()).ToList(); } SelectListGroup storeFrontGroup = new SelectListGroup() { Name = "Store Front" }; storeFrontListItems = storeFrontFiles.Select(fil => new SelectListItem() { Value = fil.Name, Text = fil.Name + (fil.Name.ToLower() == selectedFileName ? " [SELECTED]" : "") + " " + fil.Length.ToByteString(), Selected = fil.Name.ToLower() == selectedFileName, Group = storeFrontGroup }).ToList(); } string clientVirtualPath = client.ProductDigitalDownloadVirtualDirectoryToMap(http.Request.ApplicationPath); string clientFolderPath = http.Server.MapPath(clientVirtualPath); List <SelectListItem> clientListItems = new List <SelectListItem>(); if (System.IO.Directory.Exists(clientFolderPath)) { DirectoryInfo clientFolder = new System.IO.DirectoryInfo(clientFolderPath); List <FileInfo> clientFiles = clientFolder.EnumerateFiles(searchPattern).ToList(); if (filterForAudio && filterForImages) { clientFiles = clientFiles.Where(f => f.Name.FileExtensionIsAudio() || f.Name.FileExtensionIsImage()).ToList(); } else if (filterForImages) { clientFiles = clientFiles.Where(f => f.Name.FileExtensionIsImage()).ToList(); } else if (filterForAudio) { clientFiles = clientFiles.Where(f => f.Name.FileExtensionIsAudio()).ToList(); } SelectListGroup clientGroup = new SelectListGroup() { Name = "Client" }; clientListItems = clientFiles.Select(fil => new SelectListItem() { Value = fil.Name, Text = fil.Name + (fil.Name.ToLower() == selectedFileName ? " [SELECTED]" : "") + " " + fil.Length.ToByteString(), Selected = fil.Name.ToLower() == selectedFileName, Group = clientGroup }).ToList(); } string serverVirtualPath = "~/Content/Server/DigitalDownload/Products"; string serverFolderPath = http.Server.MapPath(serverVirtualPath); List <SelectListItem> serverListItems = new List <SelectListItem>(); if (System.IO.Directory.Exists(serverFolderPath)) { DirectoryInfo serverFolder = new System.IO.DirectoryInfo(serverFolderPath); List <FileInfo> serverFiles = serverFolder.EnumerateFiles(searchPattern).ToList(); if (filterForAudio && filterForImages) { serverFiles = serverFiles.Where(f => f.Name.FileExtensionIsAudio() || f.Name.FileExtensionIsImage()).ToList(); } else if (filterForImages) { serverFiles = serverFiles.Where(f => f.Name.FileExtensionIsImage()).ToList(); } else if (filterForAudio) { serverFiles = serverFiles.Where(f => f.Name.FileExtensionIsAudio()).ToList(); } SelectListGroup serverGroup = new SelectListGroup() { Name = "GStore Files" }; serverListItems = serverFiles.Select(fil => new SelectListItem() { Value = fil.Name, Text = fil.Name + (fil.Name.ToLower() == selectedFileName ? " [SELECTED]" : "") + " " + fil.Length.ToByteString(), Selected = fil.Name.ToLower() == selectedFileName, Group = serverGroup }).ToList(); } return(storeFrontListItems.Concat(clientListItems).Concat(serverListItems)); }
void WalkDirectoryTree(System.IO.DirectoryInfo root, IProgress <TheImage> progress, Form form = null, bool InvokeRequired = false, int searchDepth = 1) { IEnumerable <FileInfo> allimgfiles = null; IEnumerable <FileInfo> allJpegfiles = null; IEnumerable <FileInfo> HEICfiles = null; //IEnumerable<FileInfo> PDFfiles = null; System.IO.DirectoryInfo[] subDirs = null; if (NoOfTotalDirsFound > Globals.MaxDirectoryToSearchLimit) { return; } // First, process all the files directly under this folder try { if (Globals.PrintSelection == Globals.PrintSize.pdf) { allimgfiles = root.EnumerateFiles("*.pdf"); } else { allimgfiles = root.EnumerateFiles("*.jpg"); allJpegfiles = root.EnumerateFiles("*.jpeg"); HEICfiles = root.EnumerateFiles("*.heic"); allimgfiles = allimgfiles.Concat <FileInfo>(HEICfiles); allimgfiles = allimgfiles.Concat <FileInfo>(allJpegfiles); } } // This is thrown if even one of the files requires permissions greater // than the application provides. catch (UnauthorizedAccessException e) { // This code just writes out the message and continues to recurse. // You may decide to do something different here. For example, you // can try to elevate your privileges and access the file again. log.Add(e.Message); } catch (System.IO.DirectoryNotFoundException e) { log.Add(e.Message); } if (allimgfiles != null) { int count = 0; List <TheImage> peerImages = new List <TheImage>(); int ImageLimit; // if image count is lower than min images, leave this directory if (allimgfiles.Count() < Globals.IncludeDirectoryContainingMinImages) { return; } if (allimgfiles.Count() > Globals.IncludeMaxImages) { ImageLimit = Globals.IncludeMaxImages; } else { ImageLimit = allimgfiles.Count(); } foreach (System.IO.FileInfo fi in allimgfiles) { peerImages.Add(new TheImage() { ImageName = fi.Name, ImageFullName = fi.FullName, ImageDirName = root.Name, ImageDirFullName = root.FullName, ImageDirTotalImages = allimgfiles.Count() }); if (count >= ImageLimit - 1) { count = 0; NoOfTotalDirsFound++; if (InvokeRequired) { //Parentform.Invoke((Action<bool>)Done, true); form.Invoke( new Action <IProgress <TheImage>, System.IO.DirectoryInfo, IEnumerable <FileInfo> , List <TheImage>, int> ( Report //(prog, rt, fls, prImages, ImgLimit) => Report(prog, rt, fls, prImages, ImgLimit) ), progress, root, allimgfiles, peerImages, ImageLimit); } //form.Invoke( else { Report(progress, root, allimgfiles, peerImages, ImageLimit); //progress.Report(new ChitraKiAlbumAurVivaran() //{ // ImageName = "(" + (files.Length - ImageLimit) + ") More Images", // ImageFullName = "..\\..\\..\\pics\\vst.png", // ImageDirName = root.Name, // ImageDirFullName = root.FullName, // ImageDirTotalImages = files.Length, // PeerImages = peerImages //}); } //progress.Report(root.Name +" | " + root.FullName + " | "+fi.FullName + " | " + fi.Name + " | " + files.Length); break; } count++; } // Now find all the subdirectories under this directory. subDirs = root.GetDirectories(); //if (searchDepth >0) //{ // foreach (System.IO.DirectoryInfo dirInfo in subDirs) // { // // Resursive call for each subdirectory. // WalkDirectoryTree(dirInfo, progress); // } //} } }
private void CreateDb(string version) { var v = version.Replace(".", "_"); var n = typeof(T).FullName; TempPath = new System.IO.DirectoryInfo($"{Path.GetTempPath()}\\{n}"); if (!TempPath.Exists) { TempPath.Create(); } DbFile = $"{TempPath.FullName}\\DB_{v}.mdf"; LogFile = $"{TempPath.FullName}\\DB_{v}.ldf"; if (File.Exists(DbFile)) { return; } // delete others.. try { foreach (var file in TempPath.EnumerateFiles()) { if (file.Exists) { try { file.Delete(); } catch (Exception ex) { Trace.WriteLine(ex.ToString()); } } } } catch (Exception ex) { Trace.WriteLine(ex.ToString()); } string DBName = $"{typeof(T).Name}_{v}"; // create.... SqlHelper.Execute($"CREATE DATABASE [{DBName}] ON PRIMARY (NAME = {DBName}_data, FILENAME='{DbFile}') LOG ON (NAME={DBName}_Log, FILENAME='{LogFile}')"); SqlConnectionStringBuilder sqlCnstr = CreateConnectionStringBuilder(DBName); MockDatabaseContext.Current.ConnectionString = sqlCnstr.ToString(); Exception lastError = null; try { DbContextOptionsBuilder <T> options = new DbContextOptionsBuilder <T>(); options.UseSqlServer(sqlCnstr.ConnectionString); using (var db = (T)Activator.CreateInstance(typeof(T), options.Options)) { NeuroSpeech.EFCoreLiveMigration.MigrationHelper .ForSqlServer(db) .Migrate(); //db.Talents.FirstOrDefault(); //var p = db.GetType().GetProperties().Where(x => x.PropertyType.Name.StartsWith("DbSet")).FirstOrDefault(); //var en = p.GetValue(db) as IEnumerable<object>; //foreach (var item in en) //{ // break; //} } } catch (Exception ex) { lastError = ex; } // detach... SqlHelper.Execute("USE master;"); SqlHelper.Execute($"ALTER DATABASE [{DBName}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;"); SqlHelper.ExecuteSP($"EXEC MASTER.dbo.sp_detach_db @dbname", new KeyValuePair <string, object>("@dbname", DBName)); if (lastError != null) { throw new InvalidOperationException("Database creation failed", lastError); } Trace.WriteLine("Database recreated successfully"); }
/// <summary> /// 初始化第二屏幕 /// </summary> public void Initial(int Left, int Top, int Width, int Height) { // 只有一个屏幕就没必要显示对吧 if (!Resources.GetRes().DisplaySecondMonitor || System.Windows.Forms.SystemInformation.MonitorCount <= 1 || _isInitialized) { return; } // 从服务端获取图片地址集合 string ServerImgListPath0 = Path.Combine(Resources.GetRes().ROOT, Resources.GetRes().ROOT_FOLDER, Resources.GetRes().BARS_FOLDER); #if DEBUG //ServerImgListPath0 = @"E:\Project\Resources\TradingSystem\共享的图\Restaurant\2\bars"; #endif // 本地文件夹也存在(不连接服务器共享的场景) if (Directory.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Resources.GetRes().ROOT_FOLDER, Resources.GetRes().BARS_FOLDER))) { ServerImgListPath0 = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Resources.GetRes().ROOT_FOLDER, Resources.GetRes().BARS_FOLDER); } System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(ServerImgListPath0); List <FileInfo> files = new List <FileInfo>(); try { files = dirInfo.EnumerateFiles().ToList(); } catch (Exception ex) { ExceptionPro.ExpLog(ex); } foreach (var item in files) { if (item.Extension.Equals(".jpg", StringComparison.CurrentCultureIgnoreCase) || item.Extension.Equals(".png", StringComparison.CurrentCultureIgnoreCase) || item.Extension.Equals(".gif", StringComparison.CurrentCultureIgnoreCase)) { _imgList.Add(item.FullName); } } // 现在初始化屏幕 System.Windows.Forms.Screen screen = System.Windows.Forms.Screen.FromRectangle(new System.Drawing.Rectangle(Left, Top, Width, Height)); if (System.Windows.Forms.Screen.AllScreens[0].Equals(screen)) { SecondMoniterIndex = 1; } else { SecondMoniterIndex = 0; } System.Drawing.Rectangle workingArea = System.Windows.Forms.Screen.AllScreens[SecondMoniterIndex].WorkingArea; Form _fullScreenMonitorWindow = new Form(); _fullScreenMonitorWindow.SuspendLayout(); _fullScreenMonitorWindow.Location = new System.Drawing.Point(workingArea.Left, workingArea.Top); _fullScreenMonitorWindow.Width = workingArea.Width; _fullScreenMonitorWindow.Height = workingArea.Height; _fullScreenMonitorWindow.StartPosition = FormStartPosition.Manual; _fullScreenMonitorWindow.FormBorderStyle = FormBorderStyle.None; _fullScreenMonitorWindow.WindowState = FormWindowState.Maximized; _webBrowser.Dock = DockStyle.Fill; //_webBrowser.Location = new System.Drawing.Point(0, 0); //_webBrowser.Width = 1024; //_webBrowser.Height = 768; _fullScreenMonitorWindow.Controls.Add(this._webBrowser); _fullScreenMonitorWindow.Enabled = false; _fullScreenMonitorWindow.TopMost = true; _fullScreenMonitorWindow.ShowInTaskbar = false; _fullScreenMonitorWindow.ResumeLayout(false); _fullScreenMonitorWindow.Shown += (x, y) => { if (!_isShowed) { _isShowed = true; InitialAll(); } }; _fullScreenMonitorWindow.Show(); }
private void FormatButton_Click(object sender, EventArgs e) { string parentFolderName = @fileNameTextBox.Text; string folderName = @fileNameTextBox.Text + "\\exportZip_Log"; if (Directory.Exists(parentFolderName)) { //zip作成の時の名前に使う string baseFileName = ""; logTextBox.Text = ""; //指定フォルダの中にフォルダを作り中身をコピー、そっちで作業する logTextBox.AppendText("parent Folder: " + parentFolderName + "\r\n"); logTextBox.AppendText("log Folder: " + folderName + "\r\n\r\n"); DirectoryCopy(parentFolderName, folderName, false); //フォルダにあるファイルの数を取得 int fileCount = Directory.GetFiles(folderName, "*", SearchOption.TopDirectoryOnly).Length; if (fileCount > 0) { logTextBox.AppendText("at '" + folderName + "'\r\n ファイルは" + fileCount + "個です。\r\n\r\n"); } else { logTextBox.AppendText("ファイルが存在しません。\r\n"); return; } //全てのファイル名を取得 string[] past_fileNames = new string[fileCount]; string[] fileNames = new string[fileCount]; System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(folderName); IEnumerable <System.IO.FileInfo> files = di.EnumerateFiles("*", System.IO.SearchOption.AllDirectories); int i = 0; foreach (System.IO.FileInfo f in files) { past_fileNames[i] = Path.GetFileName(f.FullName); fileNames[i++] = Path.GetFileName(f.FullName); } //ファイル名の最低限の部分の長さを数える int baseFileNameLength = -1; for (i = 0; i < fileCount; i++) { if (baseFileNameLength == -1) { baseFileNameLength = fileNames[i].LastIndexOf('.'); } else { if (fileNames[i].LastIndexOf('.') < baseFileNameLength) { baseFileNameLength = fileNames[i].LastIndexOf('.'); } } } baseFileName = fileNames[0].Substring(0, baseFileNameLength); //logTextBox.AppendText("\r\n"); //各ファイルの変換後の名前を出す for (i = 0; i < fileCount; i++) { // '-'より後を消す logTextBox.AppendText(fileNames[i] + "\r\n"); int periodPosition = fileNames[i].LastIndexOf('.'); int hyphenPosition = fileNames[i].LastIndexOf('-'); if (hyphenPosition >= baseFileNameLength) { fileNames[i] = fileNames[i].Remove(hyphenPosition, periodPosition - hyphenPosition); } logTextBox.AppendText(" -> " + fileNames[i] + "\r\n"); //拡張子を変換する //ドリルファイル(.drl)を(.txt)に変換 periodPosition = fileNames[i].LastIndexOf('.'); if (fileNames[i].Substring(baseFileNameLength + 1) == "drl") { fileNames[i] = fileNames[i].Remove(periodPosition + 1, 3); fileNames[i] += "txt"; logTextBox.AppendText(" *-> " + fileNames[i] + "\r\n"); } //基板外形データ(.gm1)を(.gko)に変換 if (fileNames[i].Substring(baseFileNameLength + 1) == "gm1") { fileNames[i] = fileNames[i].Remove(periodPosition + 1, 3); fileNames[i] += "gko"; logTextBox.AppendText(" *-> " + fileNames[i] + "\r\n"); } logTextBox.AppendText("\r\n"); } //ファイル名を変換 for (i = 0; i < fileCount; i++) { try { if (past_fileNames[i] != fileNames[i]) { File.Copy(folderName + "\\" + past_fileNames[i], folderName + "\\" + fileNames[i], true); File.Delete(folderName + "\\" + past_fileNames[i]); } } catch (Exception a) { logTextBox.AppendText(a + "\r\n"); } } //余分なファイルがあれば削除 for (i = 0; i < fileCount; i++) { int periodPosition = fileNames[i].LastIndexOf('.'); string fileExtension = fileNames[i].Substring(periodPosition + 1).ToLower(); string[] extensions = { "gbl", "gbo", "gbs", "gko", "gtl", "gto", "gts", "txt" }; bool isDelete = true; //logTextBox.AppendText(fileExtension + "\r\n"); foreach (string ext in extensions) { if (fileExtension == ext) { isDelete = false; } } if (isDelete) { //logTextBox.AppendText("DELETE:" + fileNames[i] + "\r\n"); File.Delete(folderName + "\\" + fileNames[i]); } } //フォルダの中身を(.zip)にまとめる if (zipCheckBox.Checked == true) { try { string zipPath = parentFolderName + "\\" + baseFileName + ".zip"; //同じ名前のzipファイルが存在する場合、一度消す if (File.Exists(zipPath)) { File.Delete(zipPath); } ZipFile.CreateFromDirectory(folderName, zipPath); logTextBox.AppendText("\r\n" + baseFileName + ".zipを作成しました\r\n"); } catch (Exception a) { logTextBox.AppendText(a + "\r\n"); } } } else { logTextBox.AppendText("'" + folderName + "'は存在しません。\r\n"); } }
private void Mode() { if (scenarioList.SelectedItem.ToString() != "") { int start = scenarioList.SelectedItem.ToString().LastIndexOf("】"); scenarioName.Text = scenarioList.SelectedItem.ToString().Substring(start + 1); campaignName.Text = scenarioList.SelectedItem.ToString().Substring(1, start - 1); StreamReader sr = new StreamReader(Directory.GetCurrentDirectory() + "/" + systemName.Text + "/" + "【" + campaignName.Text + "】" + scenarioName.Text + "/" + "PreData.txt", Encoding.GetEncoding("Shift_JIS")); string str = sr.ReadToEnd(); sr.Close(); int numE = str.IndexOf("\n形式:"); num.Value = int.Parse(str.Substring(3, numE - 3 - 1)); string type = str.Substring(numE + 4, 2); vsE.Checked = false; vsP.Checked = false; vsQ.Checked = false; if (type == "協力") { vsE.Checked = true; } if (type == "対立") { vsP.Checked = true; } if (type == "特殊") { vsQ.Checked = true; } preBox.Text = str.Substring(numE + 8); //カレントディレクトリ内のフォルダ列挙 System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(System.IO.Directory.GetCurrentDirectory() + "/" + systemName.Text + "/" + "【" + campaignName.Text + "】" + scenarioName.Text); IEnumerable <System.IO.FileInfo> files = di.EnumerateFiles("*", System.IO.SearchOption.TopDirectoryOnly); dataList1.Items.Clear(); dataList2.Items.Clear(); //ファイルを列挙する foreach (System.IO.FileInfo f in files) { dataList1.Items.Add(f.Name.Substring(0, f.Name.Length - 4)); dataList2.Items.Add(f.Name.Substring(0, f.Name.Length - 4)); } dataList1.Items.RemoveAt(0); dataList2.Items.RemoveAt(0); } }
public static IEnumerable <FileInfo> EnumerateFiles(this DirectoryInfo Directory, IEnumerable <string> SearchPatterns, SearchOption Options = SearchOption.TopDirectoryOnly) => SearchPatterns.SelectMany(mask => Directory.EnumerateFiles(mask, Options));
//private void HandleRename() //{ // foreach (var item in filesRenamed) // { // FileDetail fd = FileDetail.ReturnObject(item.Key); // string oCompressed = fd.CompressedName; // fd.OriginalName = item.Value; // System.IO.File.Move(oCompressed, fd.CompressedName); // Debug.Print("Renamed file {0} to {1}", oCompressed, fd.CompressedName); // Log(System.IO.Path.GetDirectoryName(oCompressed), System.IO.Path.GetFileName(oCompressed), string.Format("File renamed to: {0}", fd.CompressedName), LogColor.Amber); // } // filesRenamed.Clear(); //} void SyncWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { CtrlInvoke.ButtonEnable(btnSyncStop, true); CtrlInvoke.ButtonEnable(btnSyncStart, false); CtrlInvoke.ButtonEnable(btnExtract, false); if (this.WindowState == FormWindowState.Minimized) { notifyIcon1.ShowBalloonTip(5000, "NoPeekCloud", "Synchronizing...", ToolTipIcon.Info); } ListViewItem runLogItem = new ListViewItem(new[] { DateTime.Now.ToString("dd.MM.yy"), DateTime.Now.ToString("HH:mm:ss"), (string)e.Argument }); CtrlInvoke.SetLog(lstRunLog, runLogItem); List <FileDetail> tempFileDetail = new List <FileDetail>(); CtrlInvoke.SetText(txtLastRun, DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString()); Stopwatch stopWatch = new Stopwatch(); if (string.IsNullOrEmpty(config.PasswordText)) { MsgManager.Show("Password is empty, files will not be encrypted.", "Empty password", MessageBoxIcon.Warning); } changeTimer = -1; int totalCount = 0; try { stopWatch.Start(); CtrlInvoke.SetStatus(statusStrip1, tslStatus, "Renaming files..."); //HandleRename(); CtrlInvoke.SetStatus(statusStrip1, tslStatus, "Finding files..."); int x = 0; foreach (FolderList fl in FolderList.list) { System.IO.DirectoryInfo d = new System.IO.DirectoryInfo(fl.Source); Regex re = new Regex(@"(\.tmp|^~|^thumbs\.db$|^desktop\.ini$)", RegexOptions.IgnoreCase); fl.SourceFiles.AddRange(d.EnumerateFiles("*.*", System.IO.SearchOption.AllDirectories).Where(f => !re.IsMatch(System.IO.Path.GetFileName(f.FullName))).ToList()); System.IO.DirectoryInfo dt = new System.IO.DirectoryInfo(fl.Target); fl.CompressedFiles.AddRange(dt.GetFiles("*.*", System.IO.SearchOption.AllDirectories).Select(path => path.FullName).ToList()); totalCount += fl.SourceFiles.Count; } RemainingTime rt = new RemainingTime(totalCount, 250); CtrlInvoke.SetText(txtFileTotal, totalCount.ToString()); CtrlInvoke.SetStatus(statusStrip1, tslStatus, "Synchronizing..."); foreach (FolderList fl in FolderList.list) { Debug.Print("Working on folder: {0}", fl.Source); Debug.Indent(); foreach (var file in fl.SourceFiles) { Debug.Print("Found file: {0}", file.FullName); Debug.Indent(); CtrlInvoke.SetText(txtFileCurrent, x.ToString()); CtrlInvoke.SetText(txtProgressFolder, file.DirectoryName); CtrlInvoke.SetText(txtProgressFile, file.Name); FileDetail fd = new FileDetail(); fd.OriginalName = file.FullName; fd.OriginalPath = fl.Source; fd.OriginalHash = Crypto.GetSHA512Hash(file.FullName); fd.OriginalTime = file.LastWriteTimeUtc; fd.OriginalSize = file.Length; //fd.CompressedName = fd.CompressedNamePath; if (System.IO.File.Exists(fd.CompressedName)) { System.IO.FileInfo cFi = new System.IO.FileInfo(fd.CompressedName); //fd.CompressedHash = Crypto.GetSHA512Hash(cFi.FullName); fd.CompressedTime = cFi.LastWriteTimeUtc; fd.CompressedSize = cFi.Length; } fl.CompressedFiles.Remove(fd.CompressedName); if (FileDetail.ObjectExists(file.FullName) > 0) { Debug.Print("File exists, checking details..."); FileDetail fd2 = FileDetail.ReturnObject(file.FullName); if (fd.OriginalHash == fd2.OriginalHash && fd.OriginalSize == fd2.OriginalSize && fd.OriginalTime == fd2.OriginalTime) { Debug.Print("Files are equal, check if compressed file is correct..."); //if (fd.CompressedHash == fd2.CompressedHash && fd.CompressedSize == fd2.CompressedSize && fd.CompressedTime == fd2.CompressedTime && !config.ForceCompressedCreation) if (fd.CompressedSize == fd2.CompressedSize && fd.CompressedTime == fd2.CompressedTime && !config.ForceCompressedCreation) { Debug.Print("Compressed file checks out, do nothing..."); } else { if (!config.ForceCompressedCreation) { Debug.Print("Compressed file does not match, recreate!"); //if (fd.CompressedHash != fd2.CompressedHash) Debug.Print("Hash is different: {0} <> {1}", fd.CompressedHash, fd2.CompressedHash); if (fd.CompressedSize != fd2.CompressedSize) { Debug.Print("Size is different: {0} <> {1}", fd.CompressedSize, fd2.CompressedSize); } if (fd.CompressedTime != fd2.CompressedTime) { Debug.Print("Time is different: {0} <> {1}", fd.CompressedTime, fd2.CompressedTime); } logWriter.FileLog(file.DirectoryName, file.Name, "Compressed file does not match, recreate!", LogColor.Blue); } else { Debug.Print("Forcing creation of compressed file!"); logWriter.FileLog(file.DirectoryName, file.Name, "Forcing creation of compressed file!", LogColor.Blue); } ProcHandler.Run7zip(fd, fl); } } else { Debug.Print("Files differ, do something!"); if (fd.OriginalHash != fd2.OriginalHash) { Debug.Print("Hash is different: {0} <> {1}", fd.OriginalHash, fd2.OriginalHash); } if (fd.OriginalSize != fd2.OriginalSize) { Debug.Print("Size is different: {0} <> {1}", fd.OriginalSize, fd2.OriginalSize); } if (fd.OriginalTime != fd2.OriginalTime) { Debug.Print("Time is different: {0} <> {1}", fd.OriginalTime, fd2.OriginalTime); } logWriter.FileLog(file.DirectoryName, file.Name, "Files differ, do something!", LogColor.Amber); ProcHandler.Run7zip(fd, fl); } } else { Debug.Print("File not seen before, encrypt and add to list."); logWriter.FileLog(file.DirectoryName, file.Name, "File not seen before, encrypt and add.", LogColor.Green); //FileDetail.list.Add(fd); ProcHandler.Run7zip(fd, fl); } tempFileDetail.Add(fd); x++; SyncWorker.ReportProgress(Function.ReturnPercent(x, totalCount)); if (SyncWorker.CancellationPending) { Debug.Unindent(); break; } Debug.Unindent(); CtrlInvoke.SetText(txtRemainingTime, rt.Calculate(stopWatch.ElapsedMilliseconds, x)); } if (!SyncWorker.CancellationPending) { foreach (string deleteFile in fl.CompressedFiles) { Debug.Print("Compressed file {0} not in use, delete.", deleteFile); logWriter.FileLog(System.IO.Path.GetDirectoryName(deleteFile), System.IO.Path.GetFileName(deleteFile), "Compressed file not in use, delete.", LogColor.Red); FileHandler.DeleteFile(deleteFile); } foreach (var directory in System.IO.Directory.GetDirectories(fl.Target, "*", SearchOption.AllDirectories)) { if (System.IO.Directory.GetFiles(directory).Length == 0 && System.IO.Directory.GetDirectories(directory).Length == 0) { Debug.Print("Deleting empty folder {0}.", directory); logWriter.FileLog(directory, string.Empty, "Deleting empty folder", LogColor.Red); FileHandler.DeleteFolder(directory); } } } else { Debug.Unindent(); break; } Debug.Unindent(); } if (!SyncWorker.CancellationPending) { List <FileDetail> deleteResult = FileDetail.list.Except(tempFileDetail).ToList(); foreach (FileDetail fd in deleteResult) { Debug.Print("FileDetail entry {0} points to no file that does not exist. Delete.", fd.OriginalName); logWriter.FileLog(System.IO.Path.GetDirectoryName(fd.OriginalName), System.IO.Path.GetFileName(fd.OriginalName), "FileDetail entry not in use, delete.", LogColor.Red); } } } catch (Exception exp) { MsgManager.LaunchExceptionReporter(exp); } finally { try { if (System.IO.File.Exists(FileDetail.FileName)) { System.IO.File.Copy(FileDetail.FileName, currentFolder + "\\FileDetails.bak", true); } if (!SyncWorker.CancellationPending) { XML.SerializeList <FileDetail>(FileDetail.FileName, tempFileDetail); FileDetail.list = tempFileDetail; } } catch (Exception exp2) { MsgManager.LaunchExceptionReporter(exp2); } finally { stopWatch.Stop(); CtrlInvoke.SetText(txtSyncStopWatch, stopWatch.Elapsed.ToString()); CtrlInvoke.SetText(txtSyncNumberOfFiles, totalCount.ToString()); foreach (FolderList fl in FolderList.list) { fl.SourceFiles.Clear(); fl.CompressedFiles.Clear(); } } } }
//public static bool ContainsFile([NotNull] this DirectoryInfo directory, [NotNull] string file) => File.Exists(Path.Combine(directory.FullName, file)); // закомментировано т.к. есть в MathService public static bool ContainsFileMask([NotNull] this DirectoryInfo directory, [NotNull] string mask) => directory.EnumerateFiles(mask).Any();