/// <summary> /// Populates a combobox with scraper groups /// </summary> /// <param name="cmbScraperGroupList">The combobox.</param> /// <returns>Scraper group list</returns> public static BindingList <string> GetScraperGroupsOnDisk(ComboBoxEdit cmbScraperGroupList) { var list = new BindingList <string>(); string path = Get.FileSystemPaths.PathDirScraperGroupsMovies; try { cmbScraperGroupList.Properties.Items.Clear(); string[] scraperGroupList = FastDirectoryEnumerator.EnumarateFilesPathList( Get.FileSystemPaths.PathDirScraperGroupsMovies, "*.xml"); foreach (string f in scraperGroupList) { cmbScraperGroupList.Properties.Items.Add(Path.GetFileNameWithoutExtension(f)); list.Add(Path.GetFileNameWithoutExtension(f)); } } catch (Exception ex) { Log.WriteToLog( LogSeverity.Error, 0, "Could not load scrapers from disk", path + Environment.NewLine + ex.Message); } return(list); }
/// <summary> /// Deletes the directory. /// </summary> /// <param name="target_dir"> /// The target_dir. /// </param> public static void DeleteDirectory(string target_dir) { try { string[] files = FastDirectoryEnumerator.EnumarateFilesPathList(target_dir); string[] dirs = Directory.GetDirectories(target_dir); foreach (string file in files) { File.SetAttributes(file, FileAttributes.Normal); File.Delete(file); } foreach (string dir in dirs) { DeleteDirectory(dir); } Directory.Delete(target_dir, false); } catch (Exception ex) { Log.WriteToLog(LogSeverity.Warning, 0, "Could not remove " + target_dir, ex.Message); } }
public async Task <Stream> Load(string source) { var fileName = source.Substring(source.LastIndexOf("/images/", StringComparison.InvariantCulture) + 1); fileName = fileName.Replace('/', '_'); if (!Directory.Exists(Constants.Constants.Assets)) { Directory.CreateDirectory(Constants.Constants.Assets); } var files = FastDirectoryEnumerator.EnumerateFiles(Constants.Constants.Assets); var file = files.FirstOrDefault(a => a.Name.Contains(fileName)); if (file != null) { return(File.OpenRead(file.Path)); } using (var client = new HttpClient()) { var data = await client.GetByteArrayAsync(source); { if (data == null || data.Length == 0) { return(null); } File.WriteAllBytes(Constants.Constants.Assets + fileName, data); return(new MemoryStream(data)); } } }
/// <summary> /// Loads the movie DB. /// </summary> private static void LoadMovieDB() { string path = Get.FileSystemPaths.PathDatabases + OutputName.MovieDb + Path.DirectorySeparatorChar; Directory.CreateDirectory(path); FileData[] files = FastDirectoryEnumerator.GetFiles(path, "*.movie.gz", SearchOption.TopDirectoryOnly); MovieDBFactory.MovieDatabase.Clear(); foreach (FileData file in files) { string json = Gzip.Decompress(file.Path); var movieModel = JsonConvert.DeserializeObject(json, typeof(MovieModel)) as MovieModel; MovieDBFactory.MovieDatabase.Add(movieModel); string title = FileNaming.RemoveIllegalChars(movieModel.Title); string poster = path + title + ".poster.jpg"; string fanart = path + title + ".fanart.jpg"; if (File.Exists(poster)) { movieModel.SmallPoster = ImageHandler.LoadImage(poster); } if (File.Exists(fanart)) { movieModel.SmallFanart = ImageHandler.LoadImage(fanart); } } }
/// <summary> /// Convert a path image to a bitmap-cached image /// </summary> /// <param name="value">The value produced by the binding source.</param> /// <param name="targetType">The type of the binding target property.</param> /// <param name="parameter">The converter parameter to use.</param> /// <param name="culture">The culture to use in the converter.</param> /// <returns>Cached image</returns> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (string.IsNullOrEmpty(value?.ToString())) { return(null); } var path = value.ToString(); var fileName = path.Substring(path.LastIndexOf("/images/", StringComparison.InvariantCulture) + 1); fileName = fileName.Replace('/', '_'); var files = FastDirectoryEnumerator.EnumerateFiles(Utils.Constants.Assets); var file = files.FirstOrDefault(a => a.Name.Contains(fileName)); if (file != null) { return(new Uri(file.Path, UriKind.Absolute)); } Task.Run(async() => { using (var client = new HttpClient()) { var data = await client.GetByteArrayAsync(path); { if (data == null || data.Length == 0) { return; } File.WriteAllBytes(Utils.Constants.Assets + fileName, data); } } }); return(new Uri(path, UriKind.Absolute)); }
private static List <string> GetUnityInstallations(string root, bool useFastFileEnumerator) { if (useFastFileEnumerator) { return(FastDirectoryEnumerator.EnumerateFiles(root, "Unity.exe", SearchOption.AllDirectories) .AsParallel() .Tap(file => Console.WriteLine("Found {0}", file.Path)) .Select(file => file.Path) .ToList()); } var folders = new List <string>(); var unity = Path.Combine(root, "Unity.exe"); if (File.Exists(unity)) { Console.WriteLine("Found {0}", unity); folders.Add(unity); return(folders); } foreach (var directory in Directory.EnumerateDirectories(root)) { folders.AddRange(GetUnityInstallations(directory, useFastFileEnumerator)); } return(folders); }
public static void DeleteAllCharts() { foreach (FileData file in FastDirectoryEnumerator.EnumerateFiles(GlobalVars.CacheFolder, "*.png")) { File.Delete(file.Path); } }
/// <summary> /// Updates the 'Discovered Files' count on the main form. Ideally used when updating the form /// while an upload process is taking place /// </summary> public void RecountLibraryFiles() { try { int count = 0; foreach (var watchFolder in MainForm.WatchFolders) { foreach (var file in FastDirectoryEnumerator.EnumerateFiles(watchFolder.Path, "*.*", SearchOption.AllDirectories)) { if (Path.GetExtension(file.Name.ToLower()).In(Global.SupportedMusicFiles)) { count++; } } } MainForm.SetDiscoveredFilesLabel(count.ToString()); } catch (Exception e) { Logger.Log(e, "RecountLibraryFiles", Log.LogTypeEnum.Warning); } }
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { try { FileData[] fileData = FastDirectoryEnumerator.GetFiles(textBox1.Text, "*.msi", SearchOption.AllDirectories); filesCount = fileData.Count(); ManualResetEvent[] doneEvents = new ManualResetEvent[filesCount]; LocateMsiWorkerArea[] locateMsiWorkerAreaArray = new LocateMsiWorkerArea[filesCount]; ThreadPool.SetMaxThreads(Convert.ToInt32(numericUpDown1.Value), Convert.ToInt32(numericUpDown2.Value)); for (int i = 0; i < filesCount; i++) { doneEvents[i] = new ManualResetEvent(false); LocateMsiWorkerArea locateMsiWorkerArea = new LocateMsiWorkerArea(fileData[i].Path, doneEvents[i]); locateMsiWorkerArea.InstallGuid = this.ApplicationGuid; locateMsiWorkerAreaArray[i] = locateMsiWorkerArea; ThreadPool.QueueUserWorkItem(locateMsiWorkerArea.ThreadPoolCallback, i); locateMsiWorkerArea.Completed += locateMsiWorkerArea_Completed; } /*var res = from c in class1Array.AsParallel().WithDegreeOfParallelism(5) * where c.Result * select c.MSIPath;*/ List <ManualResetEvent[]> listDoneEvent = new List <ManualResetEvent[]>(); int lengthToSplit = 64; // 64 is maximun number of events allowed for Wait handle int arrayLength = doneEvents.Length; for (int i = 0; i < arrayLength; i = i + lengthToSplit) { ManualResetEvent[] val = new ManualResetEvent[lengthToSplit]; if (arrayLength < i + lengthToSplit) { lengthToSplit = arrayLength - i; } Array.Copy(doneEvents, i, val, 0, lengthToSplit); listDoneEvent.Add(val.Where(x => x != null).ToArray()); } foreach (ManualResetEvent[] item in listDoneEvent) { WaitHandle.WaitAll(item); } for (int i = 0; i < filesCount; i++) { if (locateMsiWorkerAreaArray[i].Result) { appMsis.Add(fileData[i].Path); } } } catch (Exception exe) { DisplayError(exe); } finally { } }
/// <summary> /// Removes all files in folder. /// </summary> /// <param name="path"> /// The path of which to remove all files /// </param> public static void RemoveAllFilesInFolder(string path) { string[] files = FastDirectoryEnumerator.EnumarateFilesPathList(path); foreach (string file in files) { File.Delete(file); } }
/// <summary> /// Gets <see cref="FileData"/> for all the files in a directory that match a /// specific filter. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against files in the path.</param> /// <returns>An object that implements <see cref="IEnumerable{FileData}"/> and /// allows you to enumerate the files in the given directory.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="path"/> is a null reference (Nothing in VB) /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="filter"/> is a null reference (Nothing in VB) /// </exception> public static FileData[] GetFiles(string path, string searchPattern, SearchOption searchOption) { IEnumerable <FileData> e = FastDirectoryEnumerator.EnumerateFiles(path, searchPattern, searchOption); List <FileData> list = new List <FileData>(e); FileData[] retval = new FileData[list.Count]; list.CopyTo(retval); return(retval); }
private void button17_Click(object sender, EventArgs e) { try { if (textBox14.Text == string.Empty) { MessageBox.Show("Please specify user name for the operations"); return; } if (checkBox5.Checked == true) { if (Directory.Exists(textBox13.Text) == false) { MessageBox.Show("Wrong directory to sync is not set"); return; } int count = 0; FileData[] files = FastDirectoryEnumerator.GetFiles(textBox2.Text, "*.wrong", checkBox4.Checked == true ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly); for (int i = 0; i < files.Length; i++) { try { File.Move(files[i].Path, textBox12.Text + "\\" + files[i].Name); count++; } catch (Exception exx) { MessageBox.Show(exx.Message); } } MessageBox.Show("Total wrong files moved to " + textBox12.Text + " are " + count); } int res = m_client.SyncFilesWithDataBase(textBox13.Text, checkBox4.Checked, textBox14.Text, 0); if (res == 0) { MessageBox.Show("Sync files is in progress"); } else { while (m_syncFileEnded == false) { Thread.Sleep(500); } m_syncFileEnded = false; } } catch (Exception err) { MessageBox.Show(err.Message); } }
public void Start() { EnableRaisingEvents = true; FileData = FastDirectoryEnumerator.EnumerateFiles( Path, Filter, this.IncludeSubdirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly).ToArray(); Timer.Start(); }
private void CollectFilesInfo(string path) { try { allFiles = FastDirectoryEnumerator.EnumerateFiles(path, "*", SearchOption.AllDirectories); allFilesCount = allFiles.Count(); maxValueProgressBar += allFilesCount; } catch (Exception ex) { logger.Log(ex.Message); return; } }
/// <summary> /// BGWs the do work. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The <see cref="System.ComponentModel.DoWorkEventArgs"/> instance containing the event data. /// </param> private static void BgwDoWork(object sender, DoWorkEventArgs e) { var mediaPathModel = e.Argument as MediaPathModel; string[] files = FastDirectoryEnumerator.EnumarateFilesPathList( mediaPathModel.MediaPath, "*.*", SearchOption.AllDirectories); var returnCollection = new List <object>(2) { mediaPathModel, files }; e.Result = returnCollection; importInProgress = false; }
protected override void Populate() { try { if (_pages == null) { DirectoryEntries files = new DirectoryEntries(this.Path, "*"); var pages = new List <BblPage>(); using (FastDirectoryEnumerator fde = (FastDirectoryEnumerator)files.GetEnumerator()) { while (fde.MoveNext()) { _cancelPopulateTask.Token.ThrowIfCancellationRequested(); var data = fde.Current; if ((data.dwFileAttributes & FileAttributes.Directory) == FileAttributes.Directory) { continue; } string path = System.IO.Path.Combine(Path, data.cFileName); string ext = System.IO.Path.GetExtension(path); if (IsImageFileExtension(ext)) { BblPage page = new BblPage(this); page.Filename = data.cFileName; page.Path = System.IO.Path.Combine(Path, data.cFileName); page.Size = data.Length; page.CreationTime = data.CreationTime; page.LastAccessTime = data.LastAccessTime; page.LastWriteTime = data.LastWriteTime; lock (_lock) { pages.Add(page); } } } } if (pages.Count == 0) { return; } pages.Sort(); lock (_lock) { _pages = new ObservableCollection <BblPage>(pages); } } } catch { UnPopulate(); } }
private int CalculateMaxProjectFileNumber(string dirPath) { int maxOrdNum = 0; foreach (FileData fd in FastDirectoryEnumerator.EnumerateFiles(dirPath, "*" + Project.ProjectFileExtension, SearchOption.TopDirectoryOnly)) { int ordNum; string tail = fd.Name.TrimStart(resourceManager.GetString("ProjectFileNameDefault").ToCharArray()) .TrimEnd(Project.ProjectFileExtension.ToCharArray()); if (int.TryParse(tail, out ordNum) && ordNum > maxOrdNum) { maxOrdNum = ordNum; } } return(maxOrdNum); }
/// <summary> /// Loads the movie sets db. /// </summary> private static void LoadMovieSets() { string path = Get.FileSystemPaths.PathDatabases + OutputName.MovieSets + Path.DirectorySeparatorChar; Directory.CreateDirectory(path); FileData[] files = FastDirectoryEnumerator.GetFiles(path, "*.MovieSet.gz", SearchOption.TopDirectoryOnly); MovieSetManager.CurrentDatabase.Clear(); foreach (FileData file in files) { string json = Gzip.Decompress(file.Path); var set = JsonConvert.DeserializeObject(json, typeof(MovieSetModel)) as MovieSetModel; MovieSetManager.CurrentDatabase.Add(set); } }
void SyncFileThread(string DirectoryToSync, bool recoursive, string userName, int SyncBy) { try { int count = 0; FileData[] files = FastDirectoryEnumerator.GetFiles(DirectoryToSync, "*.Bin", recoursive == true ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly); ulong g360Index; using (UploadHistoryLogApi m = new UploadHistoryLogApi(_writeListDir, false)) { m.LoadLogToMemoryDic(); string fileToAdd = string.Empty; Dictionary <string, bool> list = m.DicFileList; for (int i = 0; i < files.Length; i++) { if (list.ContainsKey(files[i].Path) == false) { switch (SyncBy) { case 0: q.AddFile(files[i].Path, m_startTime, files[i].CreationTime, out g360Index, userName); break; case 1: q.AddFile(files[i].Path, m_startTime, files[i].LastAccesTime, out g360Index, userName); break; case 2: q.AddFile(files[i].Path, m_startTime, files[i].LastWriteTime, out g360Index, userName); break; } count++; } } } pCallback(133, m_clientIpAddress, count.ToString(), string.Empty, "ok", 0, DateTime.Now, 0, m_FileOwnerUserName); } catch (Exception err) { pCallback(133, m_clientIpAddress, "0", string.Empty, err.Message, 0, DateTime.Now, 0, m_FileOwnerUserName); } }
/// <summary> /// Loads the TV DB db /// </summary> private static void LoadTvDB() { string path = Get.FileSystemPaths.PathDatabases + OutputName.TvDb + Path.DirectorySeparatorChar; Directory.CreateDirectory(path); FileData[] files = FastDirectoryEnumerator.GetFiles(path, "*.Series.gz", SearchOption.TopDirectoryOnly); TvDBFactory.TvDatabase.Clear(); foreach (FileData file in files) { string json = Gzip.Decompress(file.Path); var series = JsonConvert.DeserializeObject(json, typeof(Series)) as Series; string title = FileNaming.RemoveIllegalChars(series.SeriesName); string poster = path + title + ".poster.jpg"; string fanart = path + title + ".fanart.jpg"; string banner = path + title + ".banner.jpg"; if (File.Exists(poster)) { series.SmallPoster = ImageHandler.LoadImage(poster); } if (File.Exists(fanart)) { series.SmallFanart = ImageHandler.LoadImage(fanart); } if (File.Exists(banner)) { series.SmallBanner = ImageHandler.LoadImage(banner); } TvDBFactory.TvDatabase.Add(series.SeriesName, series); } TvDBFactory.GeneratePictureGallery(); TvDBFactory.GenerateMasterSeriesList(); }
private void OnTimedEvent(object source, ElapsedEventArgs e) { var compareData = FastDirectoryEnumerator.EnumerateFiles( Path, Filter, this.IncludeSubdirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly).ToArray(); bool equal = FileData.Count() == compareData.Count() && !FileData.Except(compareData, new FileDataComparer()).Any() && !compareData.Except(FileData, new FileDataComparer()).Any(); if (!equal) { var ags = new PollDiscoveredChangeArgs("File structure changed"); OnPollDiscoveredChange(this, ags); } }
public string GetFullPath(string filename, string extension = ".3ds") { if (string.IsNullOrWhiteSpace(filename)) { return null; } else { var fullPath = Path.Combine(_watchedDirectoryLocation, filename); if (File.Exists(fullPath)) { return fullPath; } else { return FastDirectoryEnumerator.EnumerateFiles(_watchedDirectoryLocation, Path.GetFileNameWithoutExtension(filename) + extension, SearchOption.AllDirectories).Select(fd => fd.Path).FirstOrDefault(); } } }
/// <summary> /// Finds the files in path. /// </summary> /// <param name="path">The files path.</param> /// <param name="type">The SearchOption type.</param> /// <returns> /// A collection of files and FileInfo collections /// </returns> public static Dictionary <string, Section> FindFilesInPath(string path, SearchOption type) { var fileCollection = new List <string>(); foreach (string ext in Get.InOutCollection.VideoExtentions) { IEnumerable <FileData> files = FastDirectoryEnumerator.EnumerateFiles( path, "*." + ext.ToLower().ToList(), SearchOption.AllDirectories); fileCollection.AddRange((from f in files select f.Path).ToList()); } return(fileCollection.ToDictionary( file => file, file => Regex.IsMatch( file, "(?<![0-9])s{0,1}([0-9]{1,2})((?:(?:e[0-9]+)+)|(?:(?:x[0-9]+)+))", RegexOptions.IgnoreCase) ? Section.Tv : Section.Movies)); }
private List <FileData> GetAssemblyFilesFromDirectories(List <string> directories) { ConcurrentDictionary <string, FileData> allAssemblies = new ConcurrentDictionary <string, FileData>(); ParallelOptions parallelOptions = new ParallelOptions(); if (Directories.Count == 1) { parallelOptions.MaxDegreeOfParallelism = 1; } Parallel.ForEach(directories, directory => { foreach (FileData assembly in FastDirectoryEnumerator.EnumerateFiles(directory, "*.dll", System.IO.SearchOption.AllDirectories)) { allAssemblies.TryAdd(assembly.Path, assembly); } }); return(allAssemblies.Values.ToList()); }
/// <summary> /// Returns the total file size of a folder. /// </summary> /// <param name="path"> /// The file path. /// </param> /// <param name="pattern"> /// The pattern. /// </param> /// <returns> /// The get directory size. /// </returns> public static long GetDirectorySize(string path, string pattern = "*.*") { const string LogCatagory = "IO > Info > GetDirectorySize"; try { if (string.IsNullOrEmpty(path) || !File.Exists(path)) { return(0); } path = path.Replace(Path.GetFileName(path), string.Empty); string[] a = FastDirectoryEnumerator.EnumarateFilesPathList(path, pattern); return(a.Select(name => new FileInfo(name)).Select(info => info.Length).Sum()); } catch (Exception ex) { Log.WriteToLog(LogSeverity.Error, LoggerName.GeneralLog, LogCatagory, ex.Message); } return(0); }
/// <summary> /// Gets <see cref="FileData"/> for all the files in a directory that match a /// specific filter. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against files in the path.</param> /// <returns>An object that implements <see cref="IEnumerable{FileData}"/> and /// allows you to enumerate the files in the given directory.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="path"/> is a null reference (Nothing in VB) /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="filter"/> is a null reference (Nothing in VB) /// </exception> public static IEnumerable <FileData> EnumerateFiles(string path, string searchPattern) { return(FastDirectoryEnumerator.EnumerateFiles(path, searchPattern, SearchOption.TopDirectoryOnly)); }
/// <summary> /// Gets <see cref="FileData"/> for all the files in a directory. /// </summary> /// <param name="path">The path to search.</param> /// <returns>An object that implements <see cref="IEnumerable{FileData}"/> and /// allows you to enumerate the files in the given directory.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="path"/> is a null reference (Nothing in VB) /// </exception> public static IEnumerable <FileData> EnumerateFiles(string path) { return(FastDirectoryEnumerator.EnumerateFiles(path, "*")); }
/// <summary> /// Converts the media path import database into a MovieModel DB. /// </summary> public static void ConvertMediaPathImportToDB() { var db = MediaPathDBFactory.GetMediaPathMoviesUnsorted(); var count = 0; MovieDBFactory.ImportProgressMaximum = db.Count; ImportDatabase.Clear(); var getFiles = new string[1]; var currentGetPathFiles = string.Empty; foreach (var file in db) { MovieDBFactory.ImportProgressCurrent = count; MovieDBFactory.ImportProgressStatus = string.Format("Processing: " + file.PathAndFileName); if (file.Path != currentGetPathFiles) { var files = FastDirectoryEnumerator.EnumerateFiles(file.Path, "*.*", SearchOption.TopDirectoryOnly); getFiles = (from f in files select f.Path).ToArray(); currentGetPathFiles = file.Path; } var movieModel = new MovieModel { Title = Tools.Importing.MovieNaming.GetMovieName(file.PathAndFileName, file.MediaPathType), Year = Tools.Importing.MovieNaming.GetMovieYear(file.PathAndFileName), ScraperGroup = file.ScraperGroup, VideoSource = file.DefaultVideoSource, NfoPathOnDisk = FindNFO(file.FilenameWithOutExt, file.Path, getFiles), PosterPathOnDisk = FindPoster(file.FilenameWithOutExt, file.Path, getFiles), FanartPathOnDisk = FindFanart(file.FilenameWithOutExt, file.Path, getFiles) }; var result = (from m in ImportDatabase where m.Title == movieModel.Title select m).ToList(); if (result.Count == 0) { if (!string.IsNullOrEmpty(movieModel.NfoPathOnDisk)) { InOut.OutFactory.LoadMovie(movieModel); movieModel.ChangedText = false; } if (!string.IsNullOrEmpty(movieModel.PosterPathOnDisk)) { movieModel.GenerateSmallPoster(movieModel.PosterPathOnDisk); movieModel.ChangedPoster = false; } if (!string.IsNullOrEmpty(movieModel.FanartPathOnDisk)) { movieModel.GenerateSmallFanart(movieModel.FanartPathOnDisk); movieModel.ChangedFanart = false; } movieModel.AssociatedFiles.AddToMediaCollection(file); ImportDatabase.Add(movieModel); } else { // result[0].AssociatedFiles.GetMediaCollection().Clear(); result[0].AssociatedFiles.AddToMediaCollection(file); } count++; } }
public MachineVersionInfo[] GetMachineVersionInfo(int fileLimit) { _eventLog.WriteEntry("GetMachineVersionInfo()..", EventLogEntryType.Information); _logger.Debug("GetMachineVersionInfo() 1"); MachineVersionInfo[] machineVersionInfos = null; _logger.Debug("GetMachineVersionInfo() 2"); try { _logger.Debug("GetMachineVersionInfo() 3"); _retrievedSoftwareInfoFiles = FastDirectoryEnumerator.GetFiles(_machineSpecificDataPathUDM, "current_software*", SearchOption.AllDirectories, fileLimit); _logger.Debug("GetMachineVersionInfo() 4"); machineVersionInfos = new MachineVersionInfo[_retrievedSoftwareInfoFiles.Length]; _logger.Debug("GetMachineVersionInfo() 5"); } catch (Exception ex) { _eventLog.WriteEntry(ex.ToString(), EventLogEntryType.Error); _logger.Error(ex.ToString()); throw; } _logger.Debug(_retrievedSoftwareInfoFiles.Length + " files will be processed."); _eventLog.WriteEntry(_retrievedSoftwareInfoFiles.Length + " files will be processed.", EventLogEntryType.Information); for (int i = 0; i < _retrievedSoftwareInfoFiles.Length; i++) { try { DateTime lastUpdatedAt; int majorVersionNumber; int minorVersionNumber; string contents = File.ReadAllText(_retrievedSoftwareInfoFiles[i]); string machineGUID = GetMachineGUIDFromPath(_retrievedSoftwareInfoFiles[i]); string[] contentsArray = contents.Split(new string[] { "||" }, StringSplitOptions.RemoveEmptyEntries); string[] versionComponents = contentsArray[1].Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries); if (!DateTime.TryParse(contentsArray[0], out lastUpdatedAt)) { continue; } if (!int.TryParse(versionComponents[0], out majorVersionNumber)) { continue; } if (!int.TryParse(versionComponents[1], out minorVersionNumber)) { continue; } machineVersionInfos[i] = new MachineVersionInfo(machineGUID, lastUpdatedAt, majorVersionNumber, minorVersionNumber); } catch (Exception ex) { _eventLog.WriteEntry(ex.ToString(), EventLogEntryType.Error); } } _logger.Debug("Retrieved " + machineVersionInfos.Length + " version info data."); return(machineVersionInfos); }
/// <summary> /// Executes the scan /// </summary> public void Process() { Stopped = false; SetStatus(); if (MainForm.WatchFolders.Count == 0) { MainForm.MusicFileRepo.DeleteAll().Wait(); MainForm.PlaylistFileRepo.DeleteAll().Wait(); MainForm.SetDiscoveredFilesLabel("0"); MainForm.SetIssuesLabel("0"); MainForm.SetUploadedLabel("0"); } CurrentMusicFiles = MainForm.MusicFileRepo.LoadAll().Result; foreach (var musicFile in CurrentMusicFiles) { CurrentProcessingFilesHash.Add(musicFile.Path); } CurrentPlaylistFiles = MainForm.PlaylistFileRepo.LoadAll().Result; foreach (var playlistFile in CurrentPlaylistFiles) { CurrentProcessingFilesHash.Add(playlistFile.Path); } // // Get files to add - Cross reference with the DB // foreach (var watchFolder in MainForm.WatchFolders) { if (MainFormAborting()) { return; } if (Directory.Exists(watchFolder.Path)) { foreach (var file in FastDirectoryEnumerator.EnumerateFiles(watchFolder.Path, "*.*", SearchOption.AllDirectories)) { try { if (MainFormAborting()) { return; } if (!CurrentProcessingFilesHash.Contains(file.Path)) { if (Path.GetExtension(file.Name.ToLower()).In(Global.SupportedMusicFiles) || Path.GetExtension(file.Name.ToLower()).In(Global.SupportedPlaylistFiles)) { NewFiles.Add(file); NewFilesHash.Add(file.Path); } } if (MainFormAborting()) { return; } if (Path.GetExtension(file.Name.ToLower()).In(Global.SupportedMusicFiles) || Path.GetExtension(file.Name.ToLower()).In(Global.SupportedPlaylistFiles)) { DiscoveredFilesHash.Add(file.Path); } } catch (Exception e) { Logger.Log( e, "FileScanner.Process - Error reading file (possibly removed): " + file.Path, Log.LogTypeEnum.Error, false); } } } else { if (MainFormAborting()) { return; } SetStatus("Error: Watch folder directory does not exists: " + watchFolder.Path.EllipsisPath(100), "Directory "); ThreadHelper.SafeSleep(5000); } } // // Get files to delete - Cross reference with the DB // foreach (var musicFile in CurrentMusicFiles) { if (MainFormAborting()) { return; } if (!DiscoveredFilesHash.Contains(musicFile.Path)) { MusicFilesToDelete.Add(musicFile); } } foreach (var playlistFile in CurrentPlaylistFiles) { if (MainFormAborting()) { return; } if (!DiscoveredFilesHash.Contains(playlistFile.Path)) { PlaylistFilesToDelete.Add(playlistFile); } } using (var conn = new SQLiteConnection("Data Source=" + Global.DbLocation + ";cache=shared")) { SetStatus(); conn.Open(); try { int count = 0; foreach (var file in NewFiles) { if (MainFormAborting(conn)) { return; } count++; if (count % 100 == 0) { MainForm.SetDiscoveredFilesLabel(count.ToString()); } SetStatus(); if (Path.GetExtension(file.Path).ToLower().In(Global.SupportedMusicFiles)) { AddMusiFileToDB(conn, new MusicFile(file.Path)); } else if (Path.GetExtension(file.Path).ToLower().In(Global.SupportedPlaylistFiles)) { AddPlaylistFileToDB(conn, new PlaylistFile(file.Path, file.LastWriteTime)); } } if (MainFormAborting(conn)) { return; } foreach (var musicFile in MusicFilesToDelete) { if (MainFormAborting(conn)) { return; } RemoveMusicFileFromDB(conn, musicFile.Path); } ; if (MainFormAborting(conn)) { return; } foreach (var playlistFile in PlaylistFilesToDelete) { if (MainFormAborting(conn)) { return; } RemovePlaylistFileFromDb(conn, playlistFile.Path); } ; MainForm.SetDiscoveredFilesLabel(MainForm.MusicFileRepo.CountAll().Result.ToString()); } catch { } conn.Close(); } SetStatus(MainForm.ConnectedToYTMusic ? "Ready" : "Waiting for YouTube Music connection", "Waiting for YouTube Music connection"); Stopped = true; }