// Process all files in the directory passed in, recurse on any directories // that are found, and process the files they contain. DirectoryList ProcessDirectory(string targetDirectory) { // Process the list of files found in the directory. string [] fileEntries = Directory.GetFiles(targetDirectory); FileData [] listOfFiles = new FileData[fileEntries.Length]; long directorySize = 0; FileData currentFile; for (int i = 0; i < fileEntries.Length; i++) { currentFile = ProcessFile(fileEntries[i]); listOfFiles[i] = currentFile; directorySize = directorySize + currentFile.fileSize; } // Recurse into subdirectories of this directory. string [] subdirectoryEntries = Directory.GetDirectories(targetDirectory); DirectoryList [] listOfDirectories = new DirectoryList[subdirectoryEntries.Length]; DirectoryList currentDirectory; for (int i = 0; i < subdirectoryEntries.Length; i++) { currentDirectory = ProcessDirectory(subdirectoryEntries[i]); listOfDirectories[0] = currentDirectory; directorySize = directorySize + currentDirectory.directorySize; } return(new DirectoryList(targetDirectory, directorySize, listOfDirectories, listOfFiles)); }
/** *@brief constructor. This creates a new assets folder in the working directory this folder will serve as the workspace. * This also sets up the folder watcher to watch for folder changes so directory structure is updated even when focus is not on the editor. * The same goes for the file watcher. */ public Workspace() { file_queue_ = new List <FileQueueData>(); Application.Current.MainWindow.GotKeyboardFocus += OnMainWindowFocus; Application.Current.MainWindow.LostKeyboardFocus += OnMainWindowFocusLost; DirectoryInfo info = new DirectoryInfo(Project.directory_path + "\\assets"); items = new DirectoryList(); root = new DirectoryItem(info.FullName, info.Name, null); root.editable = false; items.Add(root); folder_watcher_ = new FileSystemWatcher(); folder_watcher_.Path = Project.directory_path + "\\assets"; folder_watcher_.IncludeSubdirectories = true; folder_watcher_.EnableRaisingEvents = true; folder_watcher_.NotifyFilter = NotifyFilters.DirectoryName; folder_watcher_.Renamed += OnFolderWatcherRenamed; folder_watcher_.Created += OnFolderWatcherCreated; folder_watcher_.Deleted += OnFolderWatcherDeleted; file_watcher_ = new FileSystemWatcher(); file_watcher_.Path = Project.directory_path + "\\assets"; file_watcher_.IncludeSubdirectories = true; file_watcher_.EnableRaisingEvents = false; file_watcher_.Filter = "*.*"; file_watcher_.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName; file_watcher_.Renamed += OnFileWatcherRenamed; file_watcher_.Changed += FileWatcherChanged; file_watcher_.Deleted += FileWatcherDeleted; file_watcher_.Created += FileWatcherCreated; }
/** *@brief constructor. This sets up the directory item by filling in the name, path, parent and sub_dirs fields. *@param[in] folder_path (string) absolute or relative path to the folder to represent *@param[in] folder_name (string) name of the folder to represent *@param[in] parent_dir (sulphur.editor.DirectoryItem) parent directory from the directory to represent */ public DirectoryItem(string folder_path, string folder_name, DirectoryItem parent_dir) { DirectoryInfo info = new DirectoryInfo(folder_path); if (info.Exists == false) { return; } path = info.FullName; name = info.Name; parent = parent_dir; editable = true; items = new DirectoryList(); DirectoryInfo[] sub_dirs = info.GetDirectories(); relative_path = parent_dir == null?path.Remove(0, Project.directory_path.Length) : parent_dir.relative_path + path.Remove(0, parent_dir.path.Length); if (relative_path.StartsWith("\\") == true) { relative_path = relative_path.Remove(0, 1); } foreach (DirectoryInfo dir in sub_dirs) { DirectoryItem item = new DirectoryItem(dir.FullName, dir.Name, this); items.Add(item); } }
protected void BindDirectoryList() { ImageFolder = ""; DirectoryList.DataSource = Directory.GetDirectories(FileImageFolder).Select(directory => directory.Substring(directory.LastIndexOf('\\') + 1)); DirectoryList.DataBind(); DirectoryList.Items.Insert(0, "userfiles/images"); }
//public void UploadFile(IHttpContext context) //{ // throw new NotImplementedException(); //} public void SendFile(IHttpContext context) { if (DirectoryList.ContainsKey(context.Request.PathInfo)) { var filepath = DirectoryList[context.Request.PathInfo]; var lastModified = File.GetLastWriteTimeUtc(filepath).ToString("R"); context.Response.AddHeader("Last-Modified", lastModified); if (context.Request.Headers.AllKeys.Contains("If-Modified-Since")) { if (context.Request.Headers["If-Modified-Since"].Equals(lastModified)) { context.Response.SendResponse(HttpStatusCode.NotModified); return; } } context.Response.ContentType = ContentType.DEFAULT.FromExtension(filepath); context.Response.SendResponse(new FileStream(filepath, FileMode.Open)); } if (!string.IsNullOrEmpty(Prefix) && context.Request.PathInfo.StartsWith(Prefix) && !context.WasRespondedTo) { throw new FileNotFoundException(context); } }
protected void RemoveFromDirectoryList(string fullPath) { DirectoryList.Where(x => x.Value == fullPath).ToList().ForEach(pair => { string key; DirectoryList.TryRemove(pair.Key, out key); }); }
/// <summary> /// Initializes a new instance of the <see cref="BrowseResponse"/> class. /// </summary> /// <param name="directoryList">The optional directory list.</param> /// <param name="lockedDirectoryList">The optional locked directory list.</param> public BrowseResponse(IEnumerable <Directory> directoryList = null, IEnumerable <Directory> lockedDirectoryList = null) { DirectoryList = directoryList ?? Enumerable.Empty <Directory>(); DirectoryCount = DirectoryList.Count(); LockedDirectoryList = lockedDirectoryList ?? Enumerable.Empty <Directory>(); LockedDirectoryCount = LockedDirectoryList.Count(); }
protected void PopulateDirectoryList() { DirectoryList.Clear(); foreach (var item in Directory.GetFiles(FolderPath, "*", SearchOption.AllDirectories).ToList()) { AddToDirectoryList(item); } }
protected void BindDirectoryList() { LinkFolder = ""; string[] directories = Directory.GetDirectories(FileLinkFolder); directories = Array.ConvertAll <string, string>(directories, delegate(string directory) { return(directory.Substring(directory.LastIndexOf('\\') + 1)); }); DirectoryList.DataSource = directories; DirectoryList.DataBind(); DirectoryList.Items.Insert(0, "Root"); }
public Settings() { DirectoryList = new DirectoryList(); DefaultMinify = true; CompileOnSave = true; ShowSuccessMessages = false; StartWithWindows = true; StartMinified = false; UseGloballyInstalledLess = false; }
public void DirListTestInvalid() { Task task = new Task("ls", "C:\\ethetrhehtet", "1"); Job job = new Job(task, null); DirectoryList.Execute(job, null); Console.WriteLine(task.message.GetType()); // Ensure that task is marked complete Assert.IsTrue(task.status == "error"); }
public Settings() { DirectoryList = new DirectoryList(); DefaultMinify = true; CompileOnSave = true; ShowSuccessMessages = false; StartWithWindows = true; StartMinified = false; CheckForLessUpdates = true; }
private void When_get_on_directory_is_invoked() { _response = _browser.Get(Route, with => { with.Query("directory", _directory); with.HttpRequest(); with.Header("Accept", "application/json"); }).GetAwaiter().GetResult(); _acutalDirList = JsonConvert.DeserializeObject <DirectoryList>(_response.Body.AsString()); }
public async Task <IReadOnlyCollection <Blob> > ListAsync(ListOptions options = null, CancellationToken cancellationToken = default) { if (options == null) { options = new ListOptions() { FolderPath = "/", Recurse = true }; } GenericValidation.CheckBlobFullPath(options.FolderPath); var info = new PathInformation(options.FolderPath); int maxResults = options.MaxResults ?? ListBatchSize; var blobs = new List <Blob>(); FilesystemList filesystemList = await Client.ListFilesystemsAsync(cancellationToken : cancellationToken); IEnumerable <FilesystemItem> filesystems = filesystemList.Filesystems .Where(x => info.Filesystem == "" || x.Name == info.Filesystem) .OrderBy(x => x.Name); foreach (FilesystemItem filesystem in filesystems) { try { DirectoryList directoryList = await Client.ListDirectoryAsync( filesystem.Name, info.Path, options.Recurse, cancellationToken : cancellationToken); IEnumerable <Blob> results = directoryList.Paths .Where(x => options.FilePrefix == null || x.Name.StartsWith(options.FilePrefix)) .Select(x => new Blob($"{filesystem.Name}/{x.Name}", x.IsDirectory ? BlobItemKind.Folder : BlobItemKind.File)) .Where(x => options.BrowseFilter == null || options.BrowseFilter(x)) .OrderBy(x => x.FullPath); blobs.AddRange(results); } catch (DataLakeGen2Exception e) when(e.StatusCode == HttpStatusCode.NotFound) { } if (blobs.Count >= maxResults) { return(blobs.Take(maxResults).ToList()); } } return(blobs.ToList()); }
public SteamLibrary(string fullPath, bool isMain = false) { FullPath = fullPath; IsMain = isMain; DirectoryList.Add("SteamApps", new DirectoryInfo(Path.Combine(FullPath, "SteamApps"))); DirectoryList.Add("SteamBackups", new DirectoryInfo(Path.Combine(FullPath, "SteamBackups"))); DirectoryList.Add("Common", new DirectoryInfo(Path.Combine(DirectoryList["SteamApps"].FullName, "common"))); DirectoryList.Add("Download", new DirectoryInfo(Path.Combine(DirectoryList["SteamApps"].FullName, "downloading"))); DirectoryList.Add("Workshop", new DirectoryInfo(Path.Combine(DirectoryList["SteamApps"].FullName, "workshop"))); }
public BackupDocument() { _backupMode = BackupMode.Secure; _backupMainFolder = string.Empty; _backupTodaysDirectoryPreText = string.Empty; _backupTodaysDirectoryMiddleText = BackupTodaysDirectoryMiddleTextType.YearMonthDay; _backupTodaysDirectoryPostText = string.Empty; _directories = new DirectoryList(); _directories.CollectionChanged += (s, e) => IsDirty = true; }
public bool UpdateFileExtension() { Utilities.Utilities.log.Info("Entering UpdateFileExtension()"); bool _return = false; var fileList = DirectoryList; fileList = fileList.ConvertAll(x => x.ToUpper());//set upper case foreach (var item in CharacterDictionary) { CharacterStatus charStatus = item.Value; var charFiles = fileList.Where(p => p.Contains(charStatus.Name.ToUpper())).ToList(); //grab all the files associated with the character foreach (var file in charFiles) //update all the files { string fileExt = Path.GetExtension(file); bool validFile = fileExt.Contains(".ESS") || fileExt.Contains(".SKSE") || fileExt.Contains(".TAZ"); var fileNotUpperCase = DirectoryList.Find(p => p.ToUpper() == file); if (validFile) { if (charStatus.Hide) { if (fileExt.Contains(".ESS") || fileExt.Contains(".SKSE")) { try { File.Move(fileNotUpperCase, $"{fileNotUpperCase}{HiddenExtension}"); Utilities.Utilities.log.Info($"Renamed {fileNotUpperCase} to {fileNotUpperCase}{HiddenExtension}"); } catch (Exception e) { Utilities.Utilities.log.Error(Utilities.Utilities.GetExceptionMessage(e)); } } } else { if (fileExt.Contains(".TAZ")) { try { File.Move(fileNotUpperCase, Path.ChangeExtension(fileNotUpperCase, null)); } catch (Exception e) { Utilities.Utilities.log.Error(Utilities.Utilities.GetExceptionMessage(e)); } } } } } } Utilities.Utilities.log.Info("leaving UpdateFileExtension()"); return(_return); }
public void DirListTest() { Task task = new Task("ls", "C:\\", "1"); Job job = new Job(task, null); DirectoryList.Execute(job, null); Console.WriteLine(task.message.GetType()); // Ensure that task is marked complete Assert.IsTrue(task.status == "complete"); // Ensure we have the right type of output in the task message Assert.AreEqual(true, (task.message is List <Apfell.Structs.FileInformation>)); }
/* * Returns all the found .docx files within a directory */ public void GetFileDirectories(string files) { // Separate Directory and file name (without extension name) string fileDir = Path.GetDirectoryName(files); string fileName = Path.GetFileNameWithoutExtension(files); FileList.Add(fileName); // Append to modified file list // Check if that file has a date at the end // New file directory and old one string full_fileDir = fileDir + "\\" + Path.GetFileName(files); DirectoryList.Add(full_fileDir); // Append to directory list }
private void UpdateDirectoryFiles() { string[] files = System.IO.Directory.GetFiles(this.CurrentDirectory); DirectoryList.Clear(); foreach (string fullFile in files) { string[] split = fullFile.Split('\\'); string file = split[split.Length - 1]; string ext = Path.GetExtension(file); if (ext.ToLower() == ".dll") { DirectoryList.Add(new FileItem(file, this.CurrentDirectory + "\\" + file)); } } }
public ViewDownloadSetterViewModel(IEventAggregator eventAggregator) { this.eventAggregator = eventAggregator; #region 属性初始化 Title = DictionaryResource.GetString("DownloadSetter"); CloudDownloadIcon = NormalIcon.Instance().CloudDownload; CloudDownloadIcon.Fill = DictionaryResource.GetColor("ColorPrimary"); FolderIcon = NormalIcon.Instance().Folder; FolderIcon.Fill = DictionaryResource.GetColor("ColorPrimary"); // 下载内容 VideoContentSettings videoContent = SettingsManager.GetInstance().GetVideoContent(); DownloadAudio = videoContent.DownloadAudio; DownloadVideo = videoContent.DownloadVideo; DownloadDanmaku = videoContent.DownloadDanmaku; DownloadSubtitle = videoContent.DownloadSubtitle; DownloadCover = videoContent.DownloadCover; if (DownloadAudio && DownloadVideo && DownloadDanmaku && DownloadSubtitle && DownloadCover) { DownloadAll = true; } else { DownloadAll = false; } // 历史下载目录 DirectoryList = SettingsManager.GetInstance().GetHistoryVideoRootPaths(); string directory = SettingsManager.GetInstance().GetSaveVideoRootPath(); if (!DirectoryList.Contains(directory)) { ListHelper.InsertUnique(DirectoryList, directory, 0); } Directory = directory; // 是否使用默认下载目录 IsDefaultDownloadDirectory = SettingsManager.GetInstance().IsUseSaveVideoRootPath() == AllowStatus.YES; #endregion }
private List <String> getFiles(string path) { List <String> pathName = new List <string>(); DirectoryList.GetDirectory(path); //目录列表 // foreach (string item in DirectoryList.DirectorysList) // { // Console.WriteLine(item); // } //文件列表 foreach (string item in DirectoryList.FileList) { pathName.Add(item); } return(pathName); }
void inner_ListControl_MouseClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { return; } else if (e.Button == MouseButtons.Right) { //check source, process only DirectoryList DirectoryList dl = null; if (!(Source is DirectoryList)) { return; } var index = inner_ListControl.GetItemAtPoint(e.Location); if (index < 0) { return; } try { dl = (DirectoryList)Source; var info = dl[index]; if (info.Directory) { var dir_info = new DirectoryInfo(info.FullName); context_menu.ShowContextMenu(new DirectoryInfo[] { dir_info }, PointToScreen(e.Location)); } else { var file_info = new FileInfo(info.FullName); context_menu.ShowContextMenu(new FileInfo[] { file_info }, PointToScreen(e.Location)); } } catch (Exception ex) { Messages.ShowException(ex); } }//end right button }
/// <summary> /// 读取文件名 /// </summary> private void readFilePathList() { filePathList.Clear(); DirectoryList.GetDirectory(filesPath_tb.Text); foreach (string item in DirectoryList.FileList) { filePathList.Add(item); } file_name_dg.Rows.Clear(); foreach (String name in filePathList) { String[] path = name.Split('\\'); DataGridViewRow dr = new DataGridViewRow(); dr.CreateCells(file_name_dg); dr.Cells[0].Value = path[path.Length - 1]; file_name_dg.Rows.Add(dr); } }
/// <summary> /// 浏览文件夹事件 /// </summary> private void ExecuteBrowseCommand() { string directory = SetDirectory(); if (directory == null) { eventAggregator.GetEvent <MessageEvent>().Publish(DictionaryResource.GetString("WarningNullDirectory")); Directory = string.Empty; } else { ListHelper.InsertUnique(DirectoryList, directory, 0); Directory = directory; if (DirectoryList.Count > maxDirectoryListCount) { DirectoryList.RemoveAt(maxDirectoryListCount); } } }
/// BaseClientService: A base class for a client service which provides common /// mechanism for all services, like serialization and GZip support. /// It should be safe to use a single service instance to make server requests /// concurrently from multiple threads. /// Initializer: An initializer class for the client service private async Task Run() { // Create the service. BaseClientService.Initializer initializer = new BaseClientService.Initializer { ApplicationName = "Discovery Sample", ApiKey = CredentialsManager.GetApiKey(), }; DiscoveryService service = new DiscoveryService(initializer); // Run the request. Console.WriteLine("Executing a list request..."); DirectoryList result = await service.Apis.List().ExecuteAsync(); // Display the results. if (result.Items != null) { foreach (DirectoryList.ItemsData api in result.Items) { Console.WriteLine(api.Id + " - " + api.Title); } } }
private string GetVersion(DirectoryList.ItemsData item) { return item.Version; }
private string GetIcon32Url(DirectoryList.ItemsData item) { if (item.Icons == null) { return ""; } return item.Icons.X32 ?? ""; }
private string GetNamespace(DirectoryList.ItemsData item) { return GeneratorUtils.UpperFirstLetter(item.Version).Replace('.', '_'); }
private string GetClassName(DirectoryList.ItemsData item) { return GeneratorUtils.UpperFirstLetter(item.Name); }
public bool MoveNext(AdvanceFlags flags) { // If before beginning or after end if (fCurrentDirectoryList == null) { if (fRootDirectories == null || fRootDirectories.Length == 0) { return(false); } if (fCurrentFileIndex >= 0 && 0 != (flags & AdvanceFlags.Wrap)) { Reset(); } // if before beginning, load up the first lists if (fCurrentFileIndex < 0) { fDirectoryStack.Clear(); fCurrentDirectoryList = new DirectoryList(fRootDirectories, fIncludeExtensions.Keys); fCurrentFiles = fCurrentDirectoryList.GetCurrentFiles(); fCurrentFileIndex = 0; } // Else, after end else { return(false); } } // Else, if Advance to next folder else if ((flags & AdvanceFlags.NextFolder) != 0) { fCurrentFileIndex = int.MaxValue; } // Else, advance image else { ++fCurrentFileIndex; } // Keep trying to load up an image until success or end is reached for (; ;) { // Get next file if available if (fCurrentFiles != null && fCurrentFileIndex < fCurrentFiles.Length) { fCurrent = fCurrentFiles[fCurrentFileIndex]; return(true); } // Advance folder else { fCurrentFiles = null; fCurrentFileIndex = 0; // Load up the subFolders DirectoryList directoryList = fCurrentDirectoryList.GetSubDirectoryList(); if (directoryList.Directories.Length != 0) { fDirectoryStack.Push(fCurrentDirectoryList); fCurrentDirectoryList = directoryList; } // Else, move to the next peer folder else { ++fCurrentDirectoryList.CurrentIndex; // If all folders are used up, pop levels off the stack if (fCurrentDirectoryList.CurrentIndex >= fCurrentDirectoryList.Directories.Length) { fCurrentDirectoryList = null; while (fDirectoryStack.Count > 0) { fCurrentDirectoryList = fDirectoryStack.Pop(); ++fCurrentDirectoryList.CurrentIndex; if (fCurrentDirectoryList.CurrentIndex < fCurrentDirectoryList.Directories.Length) { break; } fCurrentDirectoryList = null; } } } // We've popped the entire stack. At the end. if (fCurrentDirectoryList == null) { if (0 == (flags & AdvanceFlags.Wrap)) { fCurrentFileIndex = 0; fCurrentFiles = null; fCurrentDirectoryList = null; fDirectoryStack.Clear(); fCurrent = null; return(false); } else { // Wrap back to the beginning fCurrentDirectoryList = new DirectoryList(fRootDirectories, fIncludeExtensions.Keys); fCurrentFileIndex = 0; } } // Get the files from the current folder fCurrentFiles = fCurrentDirectoryList.GetCurrentFiles(); } } // End of retry loop }
private string GenerateApi(DirectoryList.ItemsData api) { var tmpl = new Template(); tmpl.Add("|| *{VERSION}* | [{URL_BINARY} {FILE_BINARY}] ([{URL_SOURCE} Source]) | [{URL_XML} XmlDoc] ||"); tmpl.Add("|| [{URL_DOCU} Documentation] | " + "[https://code.google.com/apis/explorer/#_s={NAME}&_v={VERSION} APIs Explorer] ||"); string formalName = api.Name.ToUpperFirstChar(); string formalVersion = api.Version; string binFileName = string.Format("Google.Apis.{0}.{1}.dll", formalName, formalVersion); // Fill in the data. const string RELEASE_DIR = "http://contrib.google-api-dotnet-client.googlecode.com/hg/Stable"; const string BINARY_PATH = RELEASE_DIR + "/Generated/Bin/{0}Service/{1}"; var data = new Entries(); data.Add("URL_DOCU", api.DocumentationLink); data.Add("URL_BINARY", BINARY_PATH, formalName, binFileName); data.Add("URL_XML", BINARY_PATH, formalName, Path.ChangeExtension(binFileName, ".xml")); data.Add("FILE_BINARY", binFileName); data.Add("URL_SOURCE", RELEASE_DIR + "/Generated/Source/{0}", Path.ChangeExtension(binFileName, ".cs")); data.Add("NAME", api.Name); data.Add("VERSION", api.Version); return tmpl.ToString(data); }
private string GetDescription(DirectoryList.ItemsData item) { return string.Format("Googles {0} service client api. {1}", GetName(item), MakeSafe(item.Description)); }
private string GetDocumentationLink(DirectoryList.ItemsData item) { return item.DocumentationLink ?? ""; }
private string GetTitle(DirectoryList.ItemsData item) { return item.Title.IsNotNullOrEmpty() ? MakeSafe(item.Title) : GetName(item); }
/* * Called from main function for every existing file * which reads the given .docx files * and replaces the contents as required. */ public void ReadDocx(string files) { // Separate Directory and file name (without extension name) string fileDir = Path.GetDirectoryName(files); string fileName = Path.GetFileNameWithoutExtension(files); string verify_full_fileDir = fileDir + "\\" + Path.GetFileName(files); List <bool> bodyMatch = new List <bool>(); List <bool> headerMatch = new List <bool>(); List <bool> footerMatch = new List <bool>(); List <string> tempList = new List <string>(); foreach (DirectoryModel row in SelectedDocs) { // If we should modify the document if (row.ApplyChanges) { tempList.Add(row.DirectoryNames); } } // If current file is in list of to be modified documents if (tempList.Any(verify_full_fileDir.Contains)) { byte[] byteArray = File.ReadAllBytes(files); using (MemoryStream stream = new MemoryStream()) { stream.Write(byteArray, 0, (int)byteArray.Length); using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(stream, true)) { DocumentProtection dp = wordDoc.MainDocumentPart.DocumentSettingsPart.Settings.GetFirstChild <DocumentProtection>(); if (dp != null && dp.Enforcement == DocumentFormat.OpenXml.OnOffValue.FromBoolean(true)) { dp.Remove(); // Doc is protected } foreach (var change in Changes) { if (HelperFunctions.AssertNotEmptyText(change.OldText, change.NewText)) { bodyMatch.Add(ReplaceText(wordDoc, change.OldText, change.NewText)); } } foreach (var headerChange in HeaderChanges) { if (HelperFunctions.AssertNotEmptyText(headerChange.OldText, headerChange.NewText)) { headerMatch.Add(ReplaceHeader(wordDoc, headerChange.OldText, headerChange.NewText)); } } foreach (var footerChange in FooterChanges) { if (HelperFunctions.AssertNotEmptyText(footerChange.OldText, footerChange.NewText)) { footerMatch.Add(ReplaceFooter(wordDoc, footerChange.OldText, footerChange.NewText)); } } if (Metadata.Count > 0) { UpdateMetadata(wordDoc); } } bool hasBodyMatch = bodyMatch.Any(x => x); bool hasHeaderMatch = headerMatch.Any(x => x); bool hasFooterMatch = footerMatch.Any(x => x); if (hasBodyMatch || hasHeaderMatch || hasFooterMatch) { // List of files that are processed. FileList.Add(fileName); // Check if that file has a date at the end string regexTest = @"_[0-9]{2}-[0-9]{2}-[0-9]{4}"; //check for _DD-MM-YYYY // If the file name contains date, it will take it out and replace for a new one, if not does nothing fileName = Regex.Replace(fileName, regexTest, ""); fileName += "_" + CurrentDate + ".docx"; // Add new date with file etensions // New file directory and old one string new_fileDir = fileDir + "\\" + fileName; string full_fileDir = fileDir + "\\" + Path.GetFileName(files); // Replace the old by the new string newPath = files.Replace(full_fileDir, new_fileDir); DirectoryList.Add(full_fileDir); // Append to directory list File.WriteAllBytes(newPath, stream.ToArray()); Logger = new LogFile(full_fileDir, Changes, hasBodyMatch, hasHeaderMatch, hasFooterMatch, HeaderChanges, FooterChanges); Logger.CreateLogFile(); HasChangedAnything.Add(true); } else { HasChangedAnything.Add(false); } } } }
public bool SetCurrent(string path) { // Local versions of tracking variables DirectoryList directoryList = new DirectoryList(fRootDirectories, fIncludeExtensions.Keys); Stack <DirectoryList> directoryStack = new Stack <DirectoryList>(); string[] currentFiles = null; int currentFileIndex = 0; if (path == null || path.Length == 0) { return(false); } int lastSlash = path.LastIndexOf('\\'); int matchLength = -1; for (; ;) { if (directoryList.Directories.Length == 0) { return(false); } while (directoryList.CurrentIndex < directoryList.Directories.Length) { string str = directoryList.Directories[directoryList.CurrentIndex]; if (path.Length > str.Length && path.StartsWith(str, StringComparison.OrdinalIgnoreCase) && path[str.Length] == '\\') { matchLength = str.Length; break; } ++directoryList.CurrentIndex; } if (directoryList.CurrentIndex >= directoryList.Directories.Length) { return(false); } if (matchLength >= lastSlash) { break; } directoryStack.Push(directoryList); directoryList = directoryList.GetSubDirectoryList(); } currentFiles = directoryList.GetCurrentFiles(); currentFileIndex = Array.BinarySearch(currentFiles, path, FileNameComparer.Value); if (currentFileIndex < 0) { return(false); } // Found, set the local variables fDirectoryStack = directoryStack; fCurrentDirectoryList = directoryList; fCurrentFiles = currentFiles; fCurrentFileIndex = currentFileIndex; fCurrent = fCurrentFiles[fCurrentFileIndex]; return(true); }
public bool MovePrev(AdvanceFlags flags) { // If before beginning or after end if (fCurrentDirectoryList == null) { if (fRootDirectories == null || fRootDirectories.Length == 0) { return(false); } // if before beginning, load up the first lists if (fCurrentFileIndex < 0) { return(false); } // Else, after end else { // Load up the stack fDirectoryStack.Clear(); fCurrentDirectoryList = new DirectoryList(fRootDirectories, fIncludeExtensions.Keys); for (;;) { DirectoryList directoryList = fCurrentDirectoryList.GetSubDirectoryList(); if (directoryList.Directories.Length == 0) { break; } fDirectoryStack.Push(fCurrentDirectoryList); fCurrentDirectoryList = directoryList; fCurrentDirectoryList.CurrentIndex = fCurrentDirectoryList.Directories.Length - 1; } fCurrentFiles = fCurrentDirectoryList.GetCurrentFiles(); fCurrentFileIndex = fCurrentFiles.Length - 1; } } // Else, if advance to previous folder else if ((flags & AdvanceFlags.NextFolder) != 0) { fCurrentFileIndex = -1; } // Else, advance to previous image else { --fCurrentFileIndex; } // Keep trying to load up an image until success or beginning is reached for (; ;) { // Get current file if available if (fCurrentFiles != null && fCurrentFiles.Length > 0 && fCurrentFileIndex >= 0) { fCurrent = fCurrentFiles[fCurrentFileIndex]; return(true); } // Move to previous folder else { fCurrentFiles = null; fCurrentFileIndex = 0; // Pop the stack if necessary if (fCurrentDirectoryList.CurrentIndex == 0) { // We're at the very beginning. Cannot go further. if (fDirectoryStack.Count <= 0) { fCurrentFileIndex = -1; fCurrentFiles = null; fCurrentDirectoryList = null; fCurrent = null; return(false); } // Pop one directory fCurrentDirectoryList = fDirectoryStack.Pop(); } else { // Move to the previous peer folder --fCurrentDirectoryList.CurrentIndex; // Load up all subfolders for (; ;) { DirectoryList directoryList = fCurrentDirectoryList.GetSubDirectoryList(); if (directoryList.Directories.Length == 0) { break; } fDirectoryStack.Push(fCurrentDirectoryList); fCurrentDirectoryList = directoryList; fCurrentDirectoryList.CurrentIndex = fCurrentDirectoryList.Directories.Length - 1; } } // Load up all files fCurrentFiles = fCurrentDirectoryList.GetCurrentFiles(); fCurrentFileIndex = fCurrentFiles.Length - 1; } } // End of retry loop }
private string GetName(DirectoryList.ItemsData item) { return item.Name; }
public string GetApiTitle(DirectoryList.ItemsData a) { return (a.Title ?? a.Name ?? a.Description).ToUpperFirstChar(); }