/// <summary> /// Информация о файле. /// </summary> /// <returns>Дата создания, последнего изменения, последнего обращения к файлу, атрибуты файла, доступ к файлу.</returns> public string[] info() { if (SFile.Exists(fname) & fname.Length <= 260)//проверка на существование файла и корректность имени { try { string[] s = new string[1]; s[0] += "\nДата создания файла: " + SFile.GetCreationTime(fname).ToString(); //получение информации даты создания s[0] += "\nДата последнего изменения файла: " + Convert.ToString(SFile.GetLastWriteTime(fname)); //получение информации даты последнего изменения s[0] += "\nДата последнего обращения к файлу: " + Convert.ToString(SFile.GetLastAccessTime(fname)); //получение информации даты последнего обращения к файлу s[0] += "\nАтрибуты файла: " + Convert.ToString(SFile.GetAttributes(fname)); //получение информации атрибутов файла s[0] += "\nДоступ к файлу: " + Convert.ToString(SFile.GetAccessControl(fname)); //получение информации доступа к файлу return(s); } catch (Exception e) //обработка исключений для получения информации { LogForOperations("Информация о файле", e.Message); //запись в лог ошибки (если есть) throw e; } } else { LogForOperations("Получение информации о файле", "файл не существует либо содержит в своем имени более 260 символов");//запись ошибки в лог, если не выполняется условие проверки return(null); } }
private static string ShortcutTargetType(string clickedItemPath) { var shortcutTarget = ShortcutTarget(clickedItemPath); var fileAttributes = File.GetAttributes(shortcutTarget); return((fileAttributes & FileAttributes.Directory) != 0 ? "Folder" : "File"); }
public static void Empty(this DirectoryInfo directory) { File.SetAttributes(directory.FullName, File.GetAttributes(directory.FullName) & ~(FileAttributes.Hidden | FileAttributes.ReadOnly)); foreach (var file in directory.GetFiles("*", SearchOption.AllDirectories)) { try { File.SetAttributes(file.FullName, FileAttributes.Normal); file.Delete(); } catch { } } foreach (var subDirectory in directory.GetDirectories()) { try { File.SetAttributes(subDirectory.FullName, FileAttributes.Normal); subDirectory.Delete(true); } catch { } } }
/// <summary> /// Returns true if the path points to an existing directory, false if it points to a file, and null if an exception happens during the IO operations. /// </summary> public static bool?IsDirectory(string path) { try{ return(FileIO.GetAttributes(path).HasFlag(FileAttributes.Directory)); }catch (Exception) { return(null); } }
public static FileAttributes GetAttributes(string path) { if (path != null && path.Length < 240) { return(System.IO.File.GetAttributes(path)); } return(MyFile.GetAttributes(path)); }
private void RenameFiles(string path, string pattern, string resultDirectory) { if (File.GetAttributes(path).HasFlag(FileAttributes.Directory)) { RenameFilesInDirectory(path, pattern, resultDirectory); } else { RenameFile(path, pattern, resultDirectory); } }
public MonoGameFileHandle(string path, FileType fileType) { _fileType = fileType; _isDirectory = (File.GetAttributes(path) & FileAttributes.Directory) != 0; if (_isDirectory) { _directoryInfo = new DirectoryInfo(path); } else { _fileInfo = new FileInfo(path); } }
public override void Parse() { var drivePath = Directory.Exists(Path.Combine(rootFolder, "data", user.Key, "files")) ? Path.Combine(rootFolder, "data", user.Key, "files") : null; if (drivePath == null) { return; } files = new List <OCFileCache>(); folders = new List <OCFileCache>(); folderCreation = folderCreation != null ? folderCreation : DateTime.Now.ToString("dd.MM.yyyy"); foreach (var entry in storages.FileCache) { string[] paths = entry.Path.Split('/'); if (paths[0] != "files") { continue; } paths[0] = "OwnCloud’s Files " + folderCreation; entry.Path = string.Join("/", paths); if (paths.Length >= 1) { string tmpPath = drivePath; for (var i = 1; i < paths.Length; i++) { tmpPath = Path.Combine(tmpPath, paths[i]); } if (Directory.Exists(tmpPath) || File.Exists(tmpPath)) { var attr = File.GetAttributes(tmpPath); if (attr.HasFlag(FileAttributes.Directory)) { foldersCount++; folders.Add(entry); } else { filesCount++; var fi = new FileInfo(tmpPath); bytesTotal += fi.Length; files.Add(entry); } } } } }
public MonoGameFileHandle(string prefix, string path, FileType fileType) { _fileType = fileType; _prefix = prefix; path = prefix + path; _isDirectory = (File.Exists(path) || Directory.Exists(path)) && (File.GetAttributes(path) & FileAttributes.Directory) != 0; if (_isDirectory) { _directoryInfo = new DirectoryInfo(path); } else { _fileInfo = new FileInfo(path); } }
private void RenameFiles(string path, string pattern) { var resultDirectory = File.GetAttributes(path).HasFlag(FileAttributes.Directory) ? path : Path.GetDirectoryName(path); if (Path.HasExtension(path)) { RenameFile(path, pattern, resultDirectory); } else { RenameFilesInDirectory(path, pattern, resultDirectory); } }
public MonoGameFileHandle(string prefix, string path, FileType fileType) { _fileType = fileType; _prefix = prefix; _originalPath = path; path = prefix + path; if (Mdx.platform_.isDesktop()) { _isDirectory = (File.Exists(path) || Directory.Exists(path)) && (File.GetAttributes(path) & FileAttributes.Directory) != 0; if (_isDirectory) { _directoryInfo = new DirectoryInfo(path); _filename = _directoryInfo.Name; _totalBytes = -1; } else { _fileInfo = new FileInfo(path); _filename = _fileInfo.Name; _totalBytes = _fileInfo.Exists ? (int)_fileInfo.Length : 0; } } else if (Mdx.platform_.isConsole()) { _isDirectory = path.EndsWith("/"); if (_isDirectory) { _directoryInfo = new DirectoryInfo(path); _totalBytes = -1; string dirWithoutTrailingSlash = path.Substring(0, path.Length - 1); _filename = dirWithoutTrailingSlash.Substring(dirWithoutTrailingSlash.LastIndexOf('/')); } else { _fileInfo = new FileInfo(path); _filename = path.Substring(path.LastIndexOf('/') + 1); _totalBytes = _fileType.Equals(FileType.INTERNAL_) ? -1 : (_fileInfo.Exists ? (int)_fileInfo.Length : 0); } } else { throw new PlatformNotSupportedException(); } }
public override void Parse() { var drivePath = Path.Combine(rootFolder, "Drive"); if (!Directory.Exists(drivePath)) { return; } var entries = Directory.GetFileSystemEntries(drivePath, "*", SearchOption.AllDirectories); List <string> filteredEntries = new List <string>(); files = new List <string>(); folders = new List <string>(); folderCreation = folderCreation != null ? folderCreation : DateTime.Now.ToString("dd.MM.yyyy"); newParentFolder = ModuleName + " " + folderCreation; foreach (var entry in entries) { if (ShouldIgnoreFile(entry, entries)) { continue; } filteredEntries.Add(entry); } foreach (var entry in filteredEntries) { var attr = File.GetAttributes(entry); if (attr.HasFlag(FileAttributes.Directory)) { foldersCount++; folders.Add(newParentFolder + Path.DirectorySeparatorChar.ToString() + entry.Substring(drivePath.Length + 1)); } else { filesCount++; var fi = new FileInfo(entry); bytesTotal += fi.Length; files.Add(newParentFolder + Path.DirectorySeparatorChar.ToString() + entry.Substring(drivePath.Length + 1)); } } }
private static async void GetFoldersAll(string path, int indent = 0) { try { try { if ((File.GetAttributes(path) & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint) { foreach (string folder in Directory.GetDirectories(path)) { //Console.WriteLine( "{0}{1}", new string(' ', indent), Path.GetFileName(folder)); await Bot.SendTextMessageAsync(config.ID, folder); GetFoldersAll(folder, indent + 2); } } } catch (UnauthorizedAccessException) { } } catch { // Si no encuentra el directorio await Bot.SendTextMessageAsync(config.ID, "No se encontró ese directorio en ésta computadora"); } }
/// <summary> /// Get all files of the given folder which match the extensions /// </summary> /// <param name="folder">Folder where the files should be read in (recursiv)</param> /// <param name="extensions">Extension of files which should be read in</param> /// <returns>List with the paths of the files</returns> public static List <string> GetAllFiles(string folder, List <string> extensions) { var files = (from file in Directory.GetFiles(folder) let attributes = File.GetAttributes(file) where (attributes & FileAttributes.Hidden) != FileAttributes.Hidden && extensions.Contains(file.Split('.').Last().ToLower()) select file).ToList(); try { foreach (var subDir in Directory.GetDirectories(folder)) { files.AddRange(GetAllFiles(subDir, extensions)); } } catch (Exception ex) { Logger.Error($"{ex.Message} -> \"{folder}\"", ex); } return(files); }
/// <summary> /// Removes a file (or directory). /// </summary> /// <param name="path">The file or directory to remove.</param> public static bool Remove(string path) { try { //detect whether its a directory or file if ((SFile.GetAttributes(path) & FileAttributes.Directory) == FileAttributes.Directory) { Directory.Delete(path); } else { SFile.Delete(path); } return(true); } catch (Exception e) { Log.Error($"Remove path failed {path} : {e.Message}"); } return(false); }
private static string ClickedItemType(ShellExtInitServer shellServer) { if (shellServer.FolderPath != null) { return("Directory"); } var clickedItemType = "Unsupported"; var clickedItemPath = shellServer.SelectedItemPaths.First(); if (null == clickedItemPath) { throw new ArgumentNullException(clickedItemType, Strings.clickedItemPathArgumentNullException); } try { var ext = Path.GetExtension(clickedItemPath); var fileAttributes = File.GetAttributes(clickedItemPath); // @todo: Works in the debugger, but fails for shortcuts in release mode... if (".lnk" != ext) { clickedItemType = (fileAttributes & FileAttributes.Directory) != 0 ? "Folder" : "File"; } else { clickedItemType = "Folder" == ShortcutTargetType(clickedItemPath) ? "FolderShortcut" : "FileShortcut"; } return(clickedItemType); } catch (ArgumentNullException ex) { log.Error($"{ex.Message} | Path: {clickedItemPath} | (GetClickedItemType)"); throw; } }
public static bool IsDirectory(string path) { if (!Directory.Exists(path)) { return(false); } DirectoryInfo info = new DirectoryInfo(path); if (info.Exists) { return(true); } FileAttributes attr = File.GetAttributes(path); if ((attr & FileAttributes.Directory) == FileAttributes.Directory) { return(true); } return(false); }
public string AddElement(string filepath, bool makeHardLink, bool isLinkOnly) { string hash = null; string fname = Path.GetFileName(filepath); IPFSElement prevEl = ElementExists(filepath); if (prevEl != null && !isLinkOnly) { string pathToRemove = null; if (prevEl.IsHardLink) { pathToRemove = eponaSharedFolderPath + "\\" + fname; } else if (!prevEl.IsLinkOnly) { pathToRemove = prevEl.Path; } if (pathToRemove != null) { if (prevEl.FileType.Equals(FileType.FILE)) { File.Delete(pathToRemove); } else { Directory.Delete(pathToRemove); } } elements.Remove(prevEl); hash = "unshared"; } else { FileType ft; FileAttributes attr; if (!isLinkOnly) { attr = File.GetAttributes(filepath); } else { attr = File.GetAttributes(GetShortcutTargetFile(filepath)); } //detect whether its a directory or file if ((attr & FileAttributes.Directory) == FileAttributes.Directory) { ft = FileType.FOLDER; } else { ft = FileType.FILE; } string newFilePath = eponaSharedFolderPath + "\\" + fname; if (makeHardLink) { if (ft.Equals(FileType.FILE)) { CreateHardLink(newFilePath, filepath, IntPtr.Zero); hash = ExecuteCommand("add -r -Q -w \"" + newFilePath + "\""); elements.Add(new IPFSElement(fname, newFilePath, hash, true, ft, makeHardLink, isLinkOnly)); } else { // TODO: Temporarily Disabling junctions //JunctionPoint.Create(eponaSharedFolderPath + "\\" + fname, filepath, false); CreateShortcut(fname, eponaSharedFolderPath, filepath); hash = ExecuteCommand("add -r -Q -w \"" + filepath + "\""); elements.Add(new IPFSElement(fname, filepath, hash, true, ft, makeHardLink, isLinkOnly)); } //hash = ExecuteCommand("add -r -Q -w " + eponaSharedFolderPath + "\\" + fname); //elements.Add(new IPFSElement(fname, eponaSharedFolderPath + "\\" + fname, hash, true, ft, makeHardLink, isLinkOnly)); } else if (isLinkOnly) { if (fname.EndsWith(".lnk") && IsValidIPFSPath(GetShortcutTargetFile(filepath))) { hash = GetIPFSHashFromPath(GetShortcutTargetFile(filepath)); elements.Add(new IPFSElement(fname, GetShortcutTargetFile(filepath), hash, false, ft, makeHardLink, isLinkOnly)); } } } if (!File.Exists(jsonFilePath)) { File.Create(jsonFilePath); } string json = JsonConvert.SerializeObject(elements); File.SetAttributes(jsonFilePath, FileAttributes.Normal); File.WriteAllText(jsonFilePath, json); File.SetAttributes(jsonFilePath, FileAttributes.Hidden); return(hash); }
public static BitmapImage GetIconBitmapImage(string path) { path = path.Replace("/", "\\"); var bitmap = FolderIcon; var tmpPath = path.EndsWith(".lnk") ? GetExePathFromInk(path) : path; if (!File.GetAttributes(tmpPath ?? path).HasFlag(FileAttributes.Directory)) { try { bitmap = path.EndsWith(".lnk") ? (Icon.ExtractAssociatedIcon(path) ?? Icon.ExtractAssociatedIcon(GetExePathFromInk(path)))?.ToBitmap() : Icon.ExtractAssociatedIcon(path)?.ToBitmap(); } catch (Exception ex1) { if (path.Contains("Program Files (x86)")) { path = path.Replace("Program Files (x86)", "Program Files"); } try { bitmap = path.EndsWith(".lnk") ? (Icon.ExtractAssociatedIcon(path) ?? Icon.ExtractAssociatedIcon(GetExePathFromInk(path)))?.ToBitmap() : Icon.ExtractAssociatedIcon(path)?.ToBitmap(); } catch (Exception ex2) { try { Icon icon; if (path.EndsWith(".lnk")) { icon = GetIcon(path) ?? GetIcon(GetExePathFromInk(path)) ?? GetIconForExtension(path); } else { icon = GetIcon(path) ?? GetIconForExtension(path); } if (icon == null) { return(null); } bitmap = icon.ToBitmap(); } catch (Exception ex3) { Console.WriteLine($"Error:\nCause1:\n{ex1}\nCause2:\n{ex2}\nCause3:\n{ex3}\n\n"); } } } } using (var memory = new MemoryStream()) { bitmap.Save(memory, ImageFormat.Png); memory.Position = 0; var bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.StreamSource = memory; bitmapImage.CacheOption = BitmapCacheOption.OnLoad; bitmapImage.EndInit(); return(bitmapImage); } }
public static MSIO.FileAttributes GetAttributes(string path) => MSIOF.GetAttributes(path);
private void RunSpeedtestCore() { Stopping = false; SeleniumChromeDriver = new ChromeDriver(SeleniumChromeService, SeleniumChromeOptions); for (int count = 0; count < 3; count++) { SeleniumChromeDriver.Url = "https://www.brasilbandalarga.com.br/bbl/"; IWebElement button = SeleniumChromeDriver.FindElementById("btnIniciar"); button.Click(); try { while (button.Text.ToUpper() != "INICIAR NOVO TESTE" && !Stopping) { Thread.Sleep(1000); } } catch { Stopping = true; } if (!Stopping) { IWebElement medicao = SeleniumChromeDriver.FindElementById("medicao"); List <IWebElement> textos = new List <IWebElement>(medicao.FindElements(By.ClassName("textao"))); String download = textos[0].Text; String upload = textos[1].Text; IWebElement stats = medicao.FindElement(By.ClassName("text-left")); List <IWebElement> rows = new List <IWebElement>(stats.FindElements(By.ClassName("row"))); Dictionary <String, String> testdata = new Dictionary <string, string>(); foreach (IWebElement element in rows) { if (!String.IsNullOrEmpty(element.Text)) { try { List <String> separated = new List <string>(element.Text.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries)); if (separated.Count == 1) { separated.Add("-"); } if (separated.Count == 2) { testdata.Add(separated[0].Trim(), separated[1].Trim()); } } catch { } } } List <IWebElement> topstats = new List <IWebElement>(medicao.FindElements(By.ClassName("text-center"))); String provider = topstats[0].Text.Trim(); String timestamp = topstats[1].Text.Trim(); Screenshot ss = SeleniumChromeDriver.GetScreenshot(); StreamWriter sw; String logfilepath = Path.Combine(ControlSettings.SaveFolder, "log.csv"); String excelfilepath = Path.Combine(ControlSettings.SaveFolder, "Status.xlsm"); WriteAssembly("Status.xlsm", excelfilepath); if (File.Exists(logfilepath)) { sw = new StreamWriter(logfilepath, true, Encoding.UTF8); } else { sw = new StreamWriter(logfilepath, false, Encoding.UTF8); sw.WriteLine( "Timespan;Date;Time;Download;Upload;Latencia;Jitter;Perda;IP;Região Servidor;Região Teste;Operador"); } DateTime today = DateTime.Parse(timestamp); TimeSpan now = today.TimeOfDay; String date = today.Year.ToString("D4") + "-" + today.Month.ToString("D2") + "-" + today.Day.ToString("D2"); String time = now.Hours.ToString("D2") + ":" + now.Minutes.ToString("D2"); sw.WriteLine(date + " " + time + ";" + date + ";" + time + ";" + download + ";" + upload + ";" + testdata["Latência"] + ";" + testdata["Jitter"] + ";" + testdata["Perda"] + ";" + testdata["IP"] + ";" + testdata["Região Servidor"] + ";" + testdata["Região Teste"] + ";" + provider ); ss.SaveAsFile(Path.Combine(ControlSettings.SaveFolder, date.Replace("-", "") + time.Replace(":", "") + ".jpg")); sw.Close(); File.SetAttributes(logfilepath, File.GetAttributes(logfilepath) | FileAttributes.Hidden); } } SeleniumChromeDriver.Quit(); }