public virtual async Task <FileSystemResult <IDirectory> > CreateDirectoryAsync(string name, Dictionary <string, object> properties) { try { if (properties == null) { properties = new Dictionary <string, object>(); } CreateDirectory(name); DirectoryInfo dinfo = new DirectoryInfo(Path.Combine(FullName, name)); if (properties.Any(a => a.Key.Equals("ModifiedDate", StringComparison.InvariantCultureIgnoreCase))) { dinfo.LastWriteTime = (DateTime)properties.First(a => a.Key.Equals("ModifiedDate", StringComparison.InvariantCultureIgnoreCase)).Value; } if (properties.Any(a => a.Key.Equals("CreatedDate", StringComparison.InvariantCultureIgnoreCase))) { dinfo.CreationTime = (DateTime)properties.First(a => a.Key.Equals("CreatedDate", StringComparison.InvariantCultureIgnoreCase)).Value; } LocalDirectory f = new LocalDirectory(dinfo, FS); f.Parent = this; FS.Refs[f.FullName] = f; IntDirectories.Add(f); return(await Task.FromResult(new FileSystemResult <IDirectory>(f))); } catch (Exception e) { return(new FileSystemResult <IDirectory>("Error : " + e.Message)); } }
/*public static void GetFilesForImportFolder(string folderLocation, ref List<string> fileList) * { * if (Directory.Exists(folderLocation)) * { * // get root level files * fileList.AddRange(Directory.GetFiles(folderLocation, "*.*", SearchOption.TopDirectoryOnly)); * * // search sub folders * foreach (string dirName in Directory.GetDirectories(folderLocation)) * { * try * { * if (dirName.ToUpper().Contains("RECYCLE.BIN")) continue; * * fileList.AddRange(Directory.GetFiles(dirName, "*.*", SearchOption.AllDirectories)); * } * catch (Exception ex) * { * logger.Warn("Error accessing: {0} - {1}", dirName, ex.Message); * } * } * } * }*/ public static void GetFilesForImportFolder(string sDir, ref List <string> fileList) { try { // get root level files fileList.AddRange(Directory.GetFiles(sDir, "*.*", SearchOption.TopDirectoryOnly)); // search sub folders foreach (string d in Directory.GetDirectories(sDir)) { DirectoryInfo di = new DirectoryInfo(d); bool isSystem = (di.Attributes & FileAttributes.System) == FileAttributes.System; if (isSystem) { continue; } //fileList.AddRange(Directory.GetFiles(d, "*.*", SearchOption.TopDirectoryOnly)); GetFilesForImportFolder(d, ref fileList); } } catch (System.Exception excpt) { Console.WriteLine(excpt.Message); } }
private void Scan(FilterCollection sc, DirectoryInfo dInf) { // Check all files within the directory and subdirectories. foreach (var file in dInf.GetFiles("*", SearchOption.AllDirectories)) { // Check if we want to skip the directory based on the current mode and list of user excluded directories. if (_vm.ExcludedDirectorys.Contains(file.DirectoryName) || sc.FilteredDirectories.Contains(file.DirectoryName.Split('\\').Last().ToLower())) { continue; } // Incase we are trying to check a temporary file that may have now been deleted. if (file.Exists) { try { // If file was written to or created after start time and is not already in list of changes. if ((file.LastWriteTimeUtc > _timeStarted || file.CreationTimeUtc > _timeStarted)) { if (sc.FilePassesFilter(file)) { _vm.AddNewChange(file); } } } // Catch any instances where file has been deleted during checking. catch (NullReferenceException) { } } } }
private void ScanParallel(FilterCollection sc, DirectoryInfo dInf) { // Check all files within the directory and subdirectories. Parallel.ForEach(dInf.GetFiles("*", SearchOption.AllDirectories), (file) => { // Check if we want to skip the directory based on the current mode and list of user excluded directories. if (!_vm.ExcludedDirectorys.Contains(file.DirectoryName) && !sc.FilteredDirectories.Contains(file.DirectoryName.Split('\\').Last().ToLower())) { // If file was written to or created after start time and is not already in list of changes. if ((file.LastWriteTimeUtc > _timeStarted || file.CreationTimeUtc > _timeStarted) && !sc.FilteredExtensions.Contains(file.Extension.ToLower())) { bool exclude = false; // Check if filename includes excluded strings. foreach (var exculded in sc.FilteredStrings) { // Convert both comparion strings to lower in order to prevent false negatives. if (file.FullName.ToLower().Contains(exculded.ToLower())) { // Can't use continue or break to skip file here as this is in a sub-loop. exclude = true; break; } } if (!exclude) { _vm.AddNewChange(file); } } } }); }
public EnumDirectory(DirectoryInfo directoryInfo, string pattern = null) { this.directoryInfo = directoryInfo; if (pattern == null) pattern = "*.*"; this.directoryEnum = directoryInfo.EnumerateDirectories(pattern).GetEnumerator(); }
public EnumDirectory(string directory, string pattern = null) { this.directoryInfo = new DirectoryInfo(directory); if (pattern == null) pattern = "*.*"; this.directoryEnum = directoryInfo.EnumerateDirectories(pattern).GetEnumerator(); }
public static Try <UDecimal> TryGetFolderSize(Some <string> folder) => () => { var folderSize = new DirectoryInfo(folder).GetFilesSafe("*.*", SearchOption.AllDirectories) .Sum(f => f.Length); var folderSizeInGb = new UDecimal(folderSize / 1024.0M / 1024.0M / 1024.0M); return(new Result <UDecimal>(folderSizeInGb)); };
public EnumDirectory(DirectoryInfo directoryInfo, string pattern = null) { this.directoryInfo = directoryInfo; if (pattern == null) { pattern = "*.*"; } this.directoryEnum = directoryInfo.EnumerateDirectories(pattern).GetEnumerator(); }
public EnumDirectory(string directory, string pattern = null) { this.directoryInfo = new DirectoryInfo(directory); if (pattern == null) { pattern = "*.*"; } this.directoryEnum = directoryInfo.EnumerateDirectories(pattern).GetEnumerator(); }
public static IEnumerable <FileInfo> GetFilesSafe(this DirectoryInfo directory, Some <string> searchPattern, SearchOption searchOption) { var files = TryGetFiles(directory, searchPattern).Try().Match(fs => fs, exception => Array.Empty <FileInfo>()); var subDirectories = TryGetDirectories(directory, searchPattern).Try().Match(fs => fs, exception => Array.Empty <DirectoryInfo>()); var subFiles = searchOption == SearchOption.AllDirectories ? subDirectories.SelectMany(info => GetFilesSafe(info, searchPattern, searchOption)).ToArray() : Enumerable.Empty <FileInfo>(); return(files.Concat(subFiles)); }
public static bool IsDirectoryEmpty(DirectoryInfo directoryInfo) { if (directoryInfo.EnumerateDirectories().FirstOrDefault() != null) { return(false); } if (directoryInfo.EnumerateFiles().FirstOrDefault() != null) { return(false); } return(true); }
/// <summary> /// Test if path is a symbolic link /// </summary> /// <param name="path"></param> /// <returns></returns> public static bool IsSymbolicDir(string path) { if (path.Length < MaxFilePathLength) { System.IO.DirectoryInfo pathInfo = new System.IO.DirectoryInfo(path); return(pathInfo.Attributes.HasFlag(FileAttributes.ReparsePoint)); } else { Pri.LongPath.DirectoryInfo pathInfo = new Pri.LongPath.DirectoryInfo(path); return(pathInfo.Attributes.HasFlag(FileAttributes.ReparsePoint)); } }
/// <summary> /// Creates a new <see cref="FileSystemController" />. /// </summary> public FileSystemController() { m_currentDirectory = null; m_currentFile = null; m_currentFileFullName = null; m_currentDirectoryPathParts = null; m_directories = null; m_files = null; m_showHiddenFilesAndDirectories = false; m_showSystemFilesAndDirectories = false; m_fileFilters = null; m_fileFilterToApply = null; }
public void Delete(string sourcePath) { if (IsFolder(sourcePath)) { Pri.LongPath.DirectoryInfo directoryInfo = new Pri.LongPath.DirectoryInfo(sourcePath); directoryInfo.Delete(true); } else { Pri.LongPath.FileInfo fileInfo = new Pri.LongPath.FileInfo(sourcePath); fileInfo.Delete(); } }
// string _folderName = "c:\\dinoch"; //private void buttonBrowse_Click(object sender, EventArgs e) //{ // var browseForFolder = new BrowseForFolder(); // var selectFolder = browseForFolder.SelectFolder("Select a file/folder", "", Handle); // if (!string.IsNullOrEmpty(selectFolder)) // { // FileOrFolderList.Add(selectFolder); // } //} public void MoveTo(string sourcePath, string tagetPath) { if (IsFolder(sourcePath)) { Pri.LongPath.DirectoryInfo directoryInfo = new Pri.LongPath.DirectoryInfo(sourcePath); directoryInfo.MoveTo(Pri.LongPath.Path.Combine(tagetPath, directoryInfo.Name)); } else { Pri.LongPath.FileInfo fileInfo = new Pri.LongPath.FileInfo(sourcePath); fileInfo.MoveTo(Pri.LongPath.Path.Combine(tagetPath, fileInfo.Name)); } }
static long DirectorySize(DirectoryInfo dInfo, bool includeSubDir) { // Enumerate all the files long totalSize = dInfo.EnumerateFiles().Sum(file => file.Length); // If Subdirectories are to be included if (includeSubDir) { // Enumerate all sub-directories totalSize += dInfo.EnumerateDirectories().Sum(dir => DirectorySize(dir, true)); } return totalSize; }
static void Main(string[] args) { //Works fine System.IO.DirectoryInfo sysDirectory = new System.IO.DirectoryInfo("C:\\TEST"); sysDirectory.EnumerateFiles(); //Does not compile: //'Pri.LongPath.DirectoryInfo' does not contain a definition for 'EnumerateFiles' //and no extension method 'EnumerateFiles' accepting a first argument of type //'Pri.LongPath.DirectoryInfo' could be found (are you missing a using directive or an assembly reference?) Pri.LongPath.DirectoryInfo longDirectory = new Pri.LongPath.DirectoryInfo("C:\\TEST"); longDirectory.EnumerateFiles(); }
static long DirectorySize(DirectoryInfo dInfo, bool includeSubDir) { // Enumerate all the files long totalSize = dInfo.EnumerateFiles().Sum(file => file.Length); // If Subdirectories are to be included if (includeSubDir) { // Enumerate all sub-directories totalSize += dInfo.EnumerateDirectories().Sum(dir => DirectorySize(dir, true)); } return(totalSize); }
public override async Task <FileSystemResult> RenameAsync(string newname) { if (string.Equals(Name, newname)) { return(new FileSystemResult("Unable to rename, names are the same")); } string parentPath = Path.GetDirectoryName(FullName); string newfullname = Path.Combine(parentPath, newname); Directory.Move(FullName, newfullname); DirectoryInfo dinfo = new DirectoryInfo(newfullname); _directory = dinfo; return(await Task.FromResult(new FileSystemResult())); }
private void DatePicker_SelectedDateChanged(object sender, SelectionChangedEventArgs e) { if (string.IsNullOrEmpty(_currentPath)) { return; } DatePicker dp = sender as DatePicker; if (dp == null) { lblStatus.Text = "Error getting selected date."; return; } try { changes = new List <ChangedFile>(); lstChanegs.Items.Clear(); btnSave.IsEnabled = false; btnSave.Visibility = Visibility.Hidden; DirectoryInfo dInf = new DirectoryInfo(_currentPath); foreach (var fileInfo in dInf.GetFiles("*", System.IO.SearchOption.AllDirectories)) { if (fileInfo.CreationTimeUtc >= dp.SelectedDate || fileInfo.LastWriteTimeUtc >= dp.SelectedDate) { if (Globals.SelectedFilter.FilePassesFilter(fileInfo)) { changes.Add(fileInfo); lstChanegs.Items.Add(fileInfo); } } } lblStatus.Text = "Total Changes: " + changes.Count; if (changes.Count > 0) { btnSave.IsEnabled = true; btnSave.Visibility = Visibility.Visible; } } catch (Exception ex) { lblStatus.Text = ex.Message; } }
public void TestGetCreationTime() { var tempLongPathFilename = Path.Combine(uncDirectory, Path.GetRandomFileName()); Directory.CreateDirectory(tempLongPathFilename); try { var dateTime = Directory.GetCreationTime(tempLongPathFilename); var fi = new DirectoryInfo(tempLongPathFilename); Assert.AreEqual(fi.CreationTime, dateTime); } finally { Directory.Delete(tempLongPathFilename); } }
public void TestSetCreationTimeUtc() { var tempLongPathFilename = Path.Combine(uncDirectory, Path.GetRandomFileName()); Directory.CreateDirectory(tempLongPathFilename); try { DateTime dateTime = DateTime.UtcNow.AddDays(1); Directory.SetCreationTimeUtc(tempLongPathFilename, dateTime); var di = new DirectoryInfo(tempLongPathFilename); Assert.AreEqual(di.CreationTimeUtc, dateTime); } finally { Directory.Delete(tempLongPathFilename); } }
/// <summary> /// Creates a new <see cref="FileSystemController" />. /// </summary> public FileSystemController() { m_currentDirectory = null; m_currentFile = null; m_currentFileFullName = null; m_currentDirectoryPathParts = null; m_directories = null; m_files = null; m_showHiddenFilesAndDirectories = false; m_showSystemFilesAndDirectories = false; m_fileFilters = null; m_fileFilterToApply = null; m_forceFileExtensionOfFileFilter = false; m_selectedDirectories = new HashSet <DirectoryInfo>(); m_selectedFiles = new HashSet <FileInfo>(); }
public override async Task <FileSystemResult> RenameAsync(string newname) { if (string.Equals(Name, newname)) { return(new FileSystemResult("Unable to rename, names are the same")); } string oldFullname = this.FullName; string newfullname = Path.Combine(Parent.FullName, newname); Directory.Move(FullName, newfullname); FS.Refs.Remove(oldFullname); DirectoryInfo dinfo = new DirectoryInfo(newfullname); _directory = dinfo; FS.Refs[FullName] = this; return(await Task.FromResult(new FileSystemResult())); }
public void TestSetLastAccessTime() { var tempLongPathFilename = Path.Combine(uncDirectory, Path.GetRandomFileName()); Directory.CreateDirectory(tempLongPathFilename); try { DateTime dateTime = DateTime.Now.AddDays(1); Directory.SetLastAccessTime(tempLongPathFilename, dateTime); var fi = new DirectoryInfo(tempLongPathFilename); Assert.AreEqual(fi.LastAccessTime, dateTime); } finally { Directory.Delete(tempLongPathFilename); } }
public static Task <Result <DesktopDataInfo> > GetDesktopDataInfo() { //get desktop folder var desktopDirectory = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)); //get desktop files var allFiles = desktopDirectory.GetFiles("*.*", SearchOption.AllDirectories); var allNonShortcutFiles = allFiles .Where(info => !info.Name.EndsWith(".lnk", StringComparison.InvariantCulture)) .Where(info => !info.Name.EndsWith("desktop.ini", StringComparison.InvariantCulture)) .ToArray(); var numberOfAllNonShortcutFiles = allNonShortcutFiles.Length; var sizeofAllNonShortcutFilesInBytes = allNonShortcutFiles.Sum(info => info.Length); return(Task.FromResult(new Result <DesktopDataInfo>(new DesktopDataInfo { HasDesktopData = numberOfAllNonShortcutFiles > 0, NumberOfFiles = numberOfAllNonShortcutFiles, TotalSizeInBytes = sizeofAllNonShortcutFilesInBytes }))); }
public void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs) { if (destDirName.StartsWith(sourceDirName)) { throw new Exception("Could not copy parent folder into child folder. This will cause infinite recursive copy"); } // Get the subdirectories for the specified directory. DirectoryInfo dir = new DirectoryInfo(sourceDirName); if (!dir.Exists) { throw new DirectoryNotFoundException( "Source directory does not exist or could not be found: " + sourceDirName); } DirectoryInfo[] dirs = dir.GetDirectories(); // If the destination directory doesn't exist, create it. if (!Directory.Exists(destDirName)) { Directory.CreateDirectory(destDirName); } // Get the files in the directory and copy them to the new location. var files = dir.GetFiles(); foreach (var file in files) { string temppath = _pathManager.Combine(destDirName, file.Name); file.CopyTo(temppath, false); } // If copying subdirectories, copy them and their contents to new location. if (!copySubDirs) { return; } foreach (DirectoryInfo subdir in dirs) { string temppath = _pathManager.Combine(destDirName, subdir.Name); DirectoryCopy(subdir.FullName, temppath, true); } }
/// <summary> /// Selects a new current directory. /// </summary> /// <param name="directory"></param> public void SelectDirectory(DirectoryInfo directory) { bool ShowFileSystemInfo(FileSystemInfo fileSystemInfo) { if ((ShowHiddenFilesAndDirectories || !fileSystemInfo.Attributes.HasFlag(FileAttributes.Hidden)) && (ShowSystemFilesAndDirectories || !fileSystemInfo.Attributes.HasFlag(FileAttributes.System))) { if (fileSystemInfo is FileInfo fileInfo && m_fileFilterToApply != null) { return(m_fileFilterToApply.IsMatch(fileInfo)); } else { return(true); } } return(false); };
public void TestCreateSubdirectoryWithFileSecurity() { var di = new DirectoryInfo(uncDirectory); var randomFileName = Path.GetRandomFileName(); Pri.LongPath.DirectoryInfo newDi = null; try { newDi = di.CreateSubdirectory(randomFileName, new DirectorySecurity()); Assert.IsNotNull(newDi); Assert.IsTrue(di.Exists); } finally { if (newDi != null) { newDi.Delete(); } } }
public void TestCreateWithFileSecurity() { var tempLongPathFilename = Path.Combine(uncDirectory, Path.GetRandomFileName()); var di = new DirectoryInfo(tempLongPathFilename); try { di.Create(new DirectorySecurity()); Assert.IsTrue(Directory.Exists(tempLongPathFilename)); } finally { di.Delete(); } }
public void TestCurrentDirectory() { var di = new DirectoryInfo("."); Assert.AreEqual(di.FullName, Directory.GetCurrentDirectory()); }
public void Run() { TaskFactory factory = new TaskFactory(_token); factory.StartNew(async() => { _timeStarted = DateTime.UtcNow; // While true will cause an endless loop, which is what we want. while (true) { // Alter delay based on scaning mode. if (ScaningMode == ScanMode.Single) { _delay = 1000; } else if (ScaningMode == ScanMode.Parallel) { _delay = 3000; } else { _delay = 0; } // While in manual mode we can sleep the thread. while (_delay == 0) { if (ScaningMode == ScanMode.Single) { _delay = 1000; break; } else if (ScaningMode == ScanMode.Parallel) { _delay = 3000; break; } else { Thread.Sleep(250); } } // If we are here we are not in manual mode and want to wait for the specified delay. await Task.Delay(_delay); // Check we have a directory to watch and settings to check against. if (!string.IsNullOrEmpty(_vm.WatchedFolder) && _vm.WatchedFolder.ToLower() != "none" && SelectedFilter != null) { // Check the directory exists. if (Directory.Exists(_vm.WatchedFolder)) { DirectoryInfo dInf = new DirectoryInfo(_vm.WatchedFolder); try { switch (ScaningMode) { case ScanMode.Single: Scan(SelectedFilter, dInf); break; case ScanMode.Parallel: ScanParallel(SelectedFilter, dInf); break; default: break; } } catch (Exception ex) { OnMessageRaised("Watcher: " + ex.Message); } finally { dInf = null; } } } } }, TaskCreationOptions.LongRunning); _source.Cancel(); }
public void TestSetCreationTimeMissingFile() { var filename = Path.Combine(uncDirectory, "gibberish.ext"); DateTime dateTime = DateTime.Now.AddDays(1); var di = new DirectoryInfo(filename); di.CreationTime = dateTime; }
public void TestSetLastWriteTimeUtc() { var tempLongPathFilename = Path.Combine(uncDirectory, Path.GetRandomFileName()); Directory.CreateDirectory(tempLongPathFilename); try { DateTime dateTime = DateTime.UtcNow.AddDays(1); Directory.SetLastWriteTimeUtc(tempLongPathFilename, dateTime); var fi = new DirectoryInfo(tempLongPathFilename); Assert.AreEqual(fi.LastWriteTimeUtc, dateTime); } finally { Directory.Delete(tempLongPathFilename); } }
public void TestSetCreationTime() { var tempLongPathFilename = Path.Combine(uncDirectory, Path.GetRandomFileName()); Directory.CreateDirectory(tempLongPathFilename); Assert.IsTrue(Directory.Exists(tempLongPathFilename)); try { DateTime dateTime = DateTime.Now.AddDays(1); Directory.SetCreationTime(tempLongPathFilename, dateTime); var di = new DirectoryInfo(tempLongPathFilename); Assert.AreEqual(di.CreationTime, dateTime); } finally { Directory.Delete(tempLongPathFilename); } }
public void TestGetAccessControlSections() { var tempLongPathFilename = Path.Combine(uncDirectory, Path.GetRandomFileName()); Directory.CreateDirectory(tempLongPathFilename); try { var di = new DirectoryInfo(tempLongPathFilename); var security = di.GetAccessControl(AccessControlSections.Access); Assert.IsNotNull(security); Assert.AreEqual(typeof(FileSystemRights), security.AccessRightType); Assert.AreEqual(typeof(FileSystemAccessRule), security.AccessRuleType); Assert.AreEqual(typeof(FileSystemAuditRule), security.AuditRuleType); Assert.IsTrue(security.AreAccessRulesCanonical); Assert.IsTrue(security.AreAuditRulesCanonical); Assert.IsFalse(security.AreAccessRulesProtected); Assert.IsFalse(security.AreAuditRulesProtected); var securityGetAccessRules = security.GetAuditRules(true, true, typeof(System.Security.Principal.NTAccount)).Cast<FileSystemAccessRule>(); Assert.AreEqual(0, securityGetAccessRules.Count()); AuthorizationRuleCollection perm = security.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)); var ntAccount = new System.Security.Principal.NTAccount(System.Security.Principal.WindowsIdentity.GetCurrent().Name); FileSystemAccessRule rule = perm.Cast<FileSystemAccessRule>().SingleOrDefault(e => ntAccount == e.IdentityReference); Assert.IsNotNull(rule); Assert.IsTrue((rule.FileSystemRights & FileSystemRights.FullControl) != 0); } finally { Directory.Delete(tempLongPathFilename); } }
public void TestExistsNonexistentDirectory() { var di = new DirectoryInfo("gibberish"); Assert.IsFalse(di.Exists); }
public void TestEnumerateFilesWithSearchRecursiveAndOption() { var di = new DirectoryInfo(uncDirectory); var randomFileName = Path.GetRandomFileName(); var newDi = di.CreateSubdirectory(randomFileName); try { var fi = new FileInfo(Path.Combine(newDi.FullName, "filename")); using (fi.Create()) { } try { Assert.AreEqual(0, di.EnumerateFiles("gibberish", SearchOption.AllDirectories).Count()); } finally { fi.Delete(); } } finally { newDi.Delete(true); } }
public void TestEnumerateFilesSearchWithResults() { var tempLongPathFilename = Path.Combine(uncDirectory, Path.GetRandomFileName()); Directory.CreateDirectory(tempLongPathFilename); try { var di = new DirectoryInfo(uncDirectory); var files = di.EnumerateFiles("*").ToArray(); Assert.AreEqual(1, files.Length); Assert.IsTrue(files.Any(f => f.Name == Filename)); } finally { Directory.Delete(tempLongPathFilename); } }
public void TestSetLastWriteTimeUtcMissingFile() { var filename = Path.Combine(uncDirectory, "gibberish.ext"); DateTime dateTime = DateTime.UtcNow.AddDays(1); var di = new DirectoryInfo(filename); di.LastWriteTimeUtc = dateTime; }
public void TestToString() { var fi = new DirectoryInfo(uncDirectory); Assert.AreEqual(fi.DisplayPath, fi.ToString()); }
public void TestGetLastWriteTime() { var tempLongPathFilename = Path.Combine(longPathDirectory, Path.GetRandomFileName()); Directory.CreateDirectory(tempLongPathFilename); try { var dateTime = Directory.GetLastWriteTime(tempLongPathFilename); var fi = new DirectoryInfo(tempLongPathFilename); Assert.AreEqual(fi.LastWriteTime, dateTime); } finally { Directory.Delete(tempLongPathFilename); } }
public void TestGetDirectoriesWithAllSearch() { var randomFileName = Path.GetRandomFileName(); var tempLongPathFilename = Path.Combine(uncDirectory, randomFileName); Directory.CreateDirectory(tempLongPathFilename); try { var di = new DirectoryInfo(uncDirectory); var dirs = di.GetDirectories("*").ToArray(); Assert.AreEqual(1, dirs.Length); Assert.IsTrue(dirs.Any(f => f.Name == randomFileName)); } finally { Directory.Delete(tempLongPathFilename); } }
public void TestGetCreationTimeUTc() { var tempLongPathFilename = Path.Combine(uncDirectory, Path.GetRandomFileName()); Directory.CreateDirectory(tempLongPathFilename); try { var dateTime = Directory.GetCreationTimeUtc(tempLongPathFilename); var fi = new DirectoryInfo(tempLongPathFilename); Assert.AreEqual(fi.CreationTimeUtc, dateTime); } finally { Directory.Delete(tempLongPathFilename); } }
public void TestGetDirectoriesWithSingleResultSubsetSearch() { var randomFileName = "TestGetDirectoriesWithSubsetSearch"; var tempLongPathFilename = Path.Combine(uncDirectory, randomFileName); Directory.CreateDirectory(tempLongPathFilename); try { var di = new DirectoryInfo(uncDirectory); var dirs = di.GetDirectories("A*").ToArray(); Assert.AreEqual(0, dirs.Length); Assert.IsFalse(dirs.Any(f => f.Name == randomFileName)); } finally { Directory.Delete(tempLongPathFilename); } }
/// <summary> /// Creates a new <see cref="DirectorySelectedEventArgs" />. /// </summary> /// <param name="routedEvent"></param> /// <param name="source">The source object</param> /// <param name="directoryInfo">The selected directory</param> public DirectorySelectedEventArgs(RoutedEvent routedEvent, object source, DirectoryInfo directoryInfo) : base(routedEvent, source) { DirectoryInfo = directoryInfo; }
public void TestGetFiles() { var di = new DirectoryInfo(uncDirectory); var files = di.GetFiles().ToArray(); Assert.AreEqual(1, files.Length); Assert.IsTrue(files.Any(f => f.Name == Filename)); }
public void TestSetLastWriteTimeUtc() { var filename = Util.CreateNewFile(uncDirectory); try { DateTime dateTime = DateTime.UtcNow.AddDays(1); var di = new DirectoryInfo(filename); di.LastWriteTimeUtc = dateTime; Assert.AreEqual(dateTime, File.GetLastWriteTimeUtc(filename)); } finally { File.Delete(filename); } }
public void TestGetFilesWithSearch() { var di = new DirectoryInfo(uncDirectory); var files = di.GetFiles("*").ToArray(); Assert.AreEqual(1, files.Length); }
public void TestGetFilesWithSearchWithNoResults() { var di = new DirectoryInfo(uncDirectory); var files = di.GetFiles("giberish").ToArray(); Assert.AreEqual(0, files.Length); }
public void TestGetFileSystemInfosWithSearch() { var di = new DirectoryInfo(uncDirectory); var randomFileName = Path.GetRandomFileName(); var newDi = di.CreateSubdirectory(randomFileName); try { var fi = new FileInfo(Path.Combine(newDi.FullName, "filename")); using (fi.Create()) { } try { Assert.AreEqual(2, di.GetFileSystemInfos("*").Count()); } finally { fi.Delete(); } } finally { newDi.Delete(true); } }
/// <summary> /// Creates a new <see cref="OpenDirectoryDialogResult" />. /// </summary> /// <param name="canceled">True if the dialog was canceled</param> /// <param name="directoryInfo">The selected directory</param> public OpenDirectoryDialogResult(bool canceled, DirectoryInfo directoryInfo) : base(canceled) { DirectoryInfo = directoryInfo; }
public void TestGetFileSystemInfosWithSearchAndOptionNoResults() { var di = new DirectoryInfo(uncDirectory); var randomFileName = Path.GetRandomFileName(); var newDi = di.CreateSubdirectory(randomFileName); try { var fi = new FileInfo(Path.Combine(newDi.FullName, "filename")); using (fi.Create()) { } try { Assert.AreEqual(0, di.GetFileSystemInfos("gibberish", SearchOption.TopDirectoryOnly).Count()); } finally { fi.Delete(); } } finally { newDi.Delete(true); } }
public void TestEnumerateDirectoriesWithSearchWithNoResults() { var randomFileName = Path.GetRandomFileName(); var tempLongPathFilename = Path.Combine(uncDirectory, randomFileName); Directory.CreateDirectory(tempLongPathFilename); try { var di = new DirectoryInfo(uncDirectory); var dirs = di.EnumerateDirectories("gibberish").ToArray(); Assert.AreEqual(0, dirs.Length); } finally { Directory.Delete(tempLongPathFilename); } }
public void TestCreateSubdirectoryWithFileSecurity() { var di = new DirectoryInfo(uncDirectory); var randomFileName = Path.GetRandomFileName(); Pri.LongPath.DirectoryInfo newDi = null; try { newDi = di.CreateSubdirectory(randomFileName, new DirectorySecurity()); Assert.IsNotNull(newDi); Assert.IsTrue(di.Exists); } finally { if (newDi != null) newDi.Delete(); } }
public void DecryptCourse(List <ListViewItem> list) { if (string.IsNullOrWhiteSpace(txtCoursePath.Text)) { MessageBox.Show("Please select course path", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } else if (string.IsNullOrWhiteSpace(txtDBPath.Text)) { MessageBox.Show("Please select database path", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } else if (string.IsNullOrWhiteSpace(txtOutputPath.Text)) { MessageBox.Show("Please select output path", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } foreach (ListViewItem item in list) { CourseItem courseItem = listCourse.Where(r => r.Course.Name == item.Name).Select(r => r).FirstOrDefault(); if (chkDecrypt.Checked) { bgwDecrypt.ReportProgress(1, new Log { Text = $"Start to decrypt course \"{courseItem.Course.Title}\"", TextColor = Color.Magenta, NewLine = true, IsError = true }); //Create new course path with the output path var newCoursePath = Path.Combine(txtOutputPath.Text, this.CleanName(courseItem.Course.Title)); DirectoryInfo courseInfo = Directory.Exists(newCoursePath) ? new DirectoryInfo(newCoursePath) : Directory.CreateDirectory(newCoursePath); if (chkCopyImage.Checked && File.Exists($"{courseItem.CoursePath}\\image.jpg")) { File.Copy($"{courseItem.CoursePath}\\image.jpg", $"{newCoursePath}\\image.jpg", true); } //Get list all modules in current course List <Module> listModules = courseItem.Course.Modules; if (listModules.Count > 0) { // integer to add 1 if index should start at 1 int startAt1 = Convert.ToInt16(chkStartModuleIndexAt1.Checked); //Get each module foreach (Module module in listModules) { //Generate module hash name string moduleHash = this.ModuleHash(module.Name, module.AuthorHandle); //Generate module path string moduleHashPath = Path.Combine(courseItem.CoursePath, moduleHash); //Create new module path with decryption name string newModulePath = Path.Combine(courseInfo.FullName, $"{(startAt1 + module.Index):00}. {module.Title}"); if (Directory.Exists(moduleHashPath)) { DirectoryInfo moduleInfo = Directory.Exists(newModulePath) ? new DirectoryInfo(newModulePath) : Directory.CreateDirectory(newModulePath); //Decrypt all videos in current module folder this.DecryptAllVideos(moduleHashPath, module, moduleInfo.FullName); } else { bgwDecrypt.ReportProgress(1, new Log { Text = $"Folder {moduleHash} not found in the current course path", TextColor = Color.Red, NewLine = true, IsError = true }); } } } bgwDecrypt.ReportProgress(1, new Log { Text = $"Decrypt \"{courseItem.Course.Title}\" complete!", TextColor = Color.Magenta, NewLine = true, IsError = true }); } if (chkDelete.Checked) { try { Directory.Delete(courseItem.CoursePath, true); } catch (Exception ex) { bgwDecrypt.ReportProgress(1, new Log { Text = $"Delete folder course {courseItem.Course.Title} fail\n{ex.Message}", TextColor = Color.Gray, NewLine = true, IsError = true }); } try { RemoveCourseInDb(courseItem.CoursePath); } catch (Exception ex) { bgwDecrypt.ReportProgress(1, new Log { Text = $"Delete course {courseItem.Course.Title} from db fail\n{ex.Message}", TextColor = Color.Gray, NewLine = true, IsError = true }); } bgwDecrypt.ReportProgress(1, new Log { Text = $"Delete course {courseItem.Course.Title} success!", TextColor = Color.Magenta, NewLine = true }); } } bgwDecrypt.ReportProgress(100); }
public void TestEnumerateFiles() { var di = new DirectoryInfo(uncDirectory); var randomFileName = Path.GetRandomFileName(); var newDi = di.CreateSubdirectory(randomFileName); try { var fi = new FileInfo(Path.Combine(newDi.FullName, "filename")); using (fi.Create()) { } try { Assert.AreEqual(1, di.EnumerateFiles().Count()); } finally { fi.Delete(); } } finally { newDi.Delete(true); } }
public void TestReplaceIgnoreMergeWithReadonlyBackupPath() { var tempLongPathFilename = new StringBuilder(longPathDirectory).Append(@"\").Append("filename.ext").ToString(); var tempBackupPathName = new StringBuilder(longPathDirectory).Append(@"\readonly").ToString(); var di = new DirectoryInfo(tempBackupPathName); di.Create(); var attr = di.Attributes; di.Attributes = attr | FileAttributes.ReadOnly; var tempBackupLongPathFilename = new StringBuilder(tempBackupPathName).Append(@"\").Append("backup").ToString(); using (var fileStream = File.Create(tempLongPathFilename)) { fileStream.WriteByte(42); } var tempLongPathFilename2 = new StringBuilder(longPathDirectory).Append(@"\").Append("filename2.ext").ToString(); using (var fileStream = File.Create(tempLongPathFilename2)) { fileStream.WriteByte(52); } try { const bool ignoreMetadataErrors = true; File.Replace(tempLongPathFilename, tempLongPathFilename2, tempBackupLongPathFilename, ignoreMetadataErrors); using (var fileStream = File.OpenRead(tempLongPathFilename2)) { Assert.AreEqual(42, fileStream.ReadByte()); } Assert.IsFalse(File.Exists(tempLongPathFilename)); Assert.IsTrue(File.Exists(tempBackupLongPathFilename)); } finally { di.Attributes = attr; if (File.Exists(tempLongPathFilename)) File.Delete(tempLongPathFilename); File.Delete(tempLongPathFilename2); File.Delete(tempBackupLongPathFilename); } }
public void TestEnumerateFilesSearchWithNoResults() { var tempLongPathFilename = Path.Combine(uncDirectory, Path.GetRandomFileName()); Directory.CreateDirectory(tempLongPathFilename); try { var di = new DirectoryInfo(uncDirectory); Assert.AreEqual(0, di.EnumerateFiles("gibberish*").Count()); } finally { Directory.Delete(tempLongPathFilename); } }