private async void RemoveFileButton_OnClick(object sender, RoutedEventArgs e) { ProgressDialogController controller = await this.ShowProgressAsync("Удаление файла", "Подождите идет удаление файла на сервере..."); controller.SetIndeterminate(); FileInfoEx fileInfoEx = FilesDataGrid.SelectedItem as FileInfoEx; if (fileInfoEx != null) { try { using (FileTransferServiceClient client = new FileTransferServiceClient()) { await client.RemoveAsync(fileInfoEx); } await this.ShowMessageAsync("Удаление файла", "Файл был успешно удален!"); GetFilesList(); } catch (Exception exception) { await this.ShowMessageAsync("Ошибка", exception.Message); } } await controller.CloseAsync(); }
public bool DeleteFile(string path) { FileInfoEx f = new FileInfoEx(path); BblLibraryNode parentNode = FindChild(f.Parent); BblLibraryNode node = null; if (parentNode?.Children != null) { foreach (var n in parentNode.Children) { if (n.Path == path) { node = n; break; } } } if (parentNode != null && parentNode is BblBookDirectory) { return(parentNode.DeleteChildFile(f)); } else if (node != null) { node.OnFileSystemEntryDeleted(); } return(false); }
public static IPreviewHandler InitalizePreviewHandler(FileInfoEx file) { IPreviewHandler retVal = null; PreviewerInfo previewer = getPreviewer(file.FullName); if (previewer != null) { bool isInitialized = false; Type a = Type.GetTypeFromCLSID(previewer.CLSID, true); object o = Activator.CreateInstance(a); IInitializeWithFile fileInit = o as IInitializeWithFile; IInitializeWithStream streamInit = o as IInitializeWithStream; if (fileInit != null) { fileInit.Initialize(file.FullName, 0); isInitialized = true; } else if (streamInit != null) { FileStreamEx stream = file.OpenRead(); streamInit.Initialize((IStream)stream, 0); isInitialized = true; } if (isInitialized) { retVal = o as IPreviewHandler; } } return(retVal); }
/// this runs on a FileSystemWatcher thread /// Deletes a page, not the associated file. /// TODO: Maybe this name is confusing. It is less so in the base class. public override bool DeleteChildFile(FileInfoEx f) { if (IsPDF(f.Extension) || IsArchiveFileExtension(f.Extension)) { return(base.DeleteChildFile(f)); } else if (IsImageFileExtension(f.Extension) && IsPopulated) { var page = _pages.Where(x => x.Path == f.FullName).FirstOrDefault(); if (page == null) { return(false); } Application.Current.Dispatcher.BeginInvokeIfRequired( DispatcherPriority.Normal, new Action(() => { lock (_lock) { if (_ivps != null) { _ivps.Remove(page.Filename); } if (_pages != null) { _pages.Remove(page); } } })); } return(true); }
public virtual BblLibraryNode AddChildFile(FileInfoEx info) { if (info.Parent.FullName != Path) { return(null); } if (IsArchiveFileExtension(info.Extension) || IsPDF(info.Extension)) { BblLibraryNode b = null; if (IsArchiveFileExtension(info.Extension)) { b = new BblBookArchive(Root, this, info); } else if (IsPDF(info.Extension)) { b = new BblBookPdf(Root, this, info); } AddChild(b); return(b); } else if (IsImageFileExtension(info.Extension) && !IsBook && IsFolder && (_children == null || _children.Count == 0)) { Root.AddPromotable(this); } return(null); }
/// <summary> /// Loads the Gramps XML data. /// </summary> /// <param name="dataFolder"> /// StorageFolder to load. /// </param> /// <returns> /// Flag if Gramps Data Only loaded successfully. /// </returns> public async Task <bool> DataStorageLoadXML() { try { IFileInfoEx inputFile = new FileInfoEx(argFileName: Constants.StorageXMLFileName); App.Current.Services.GetService <IErrorNotifications>().DataLogEntryAdd("Loading existing local copy of the GRAMPS data"); { // TODO Handle no network connection Stream xmlReader = inputFile.FInfo.OpenRead(); XmlReaderSettings xmlReaderSettings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Parse }; try { localGrampsXMLdoc = XDocument.Load(xmlReader); } catch (Exception ex) { App.Current.Services.GetService <IErrorNotifications>().NotifyException("Can not load the Gramps XML file. Error in basic XML load", ex); throw; } int compareFlag = string.Compare(localGrampsXMLdoc.DocumentType.PublicId, Constants.GrampsXMLPublicId, StringComparison.CurrentCulture); if (compareFlag < 0) { ErrorInfo t = new ErrorInfo("DataStorageLoadXML", "The program can only load files with a Gramps XML version equal or greater.") { { "Minimum Version", Constants.GrampsXMLPublicId }, { "Found Version", localGrampsXMLdoc.DocumentType.PublicId }, }; App.Current.Services.GetService <IErrorNotifications>().NotifyError(t); return(false); } var nameSpaceList = localGrampsXMLdoc.Root.Attributes().Where( a => a.IsNamespaceDeclaration).GroupBy( a => a.Name.Namespace == XNamespace.None ? string.Empty : a.Name.LocalName, a => XNamespace.Get(a.Value)).ToDictionary( g => g.Key, g => g.FirstOrDefault()); ns = nameSpaceList.FirstOrDefault().Value.NamespaceName; xmlReader.Dispose(); } } catch (Exception ex) { App.Current.Services.GetService <IErrorNotifications>().NotifyException("Trying to load Gramps data only", ex); throw; } return(true); }
private bool check_readonly(FileInfoEx info) { if ((opts & DeleteFileOptions.DeleteReadonly) != DeleteFileOptions.DeleteReadonly) { return(true); } if ((info.FileAttributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { try { clear_readonly(info.FullName); return(true); } catch (Exception ex) { abort = !process_errors (string.Format (Options.GetLiteral(Options.LANG_CANNOT_CLEAR_HIDDEN_READONLY_ATTR_DESTINATION_0), info.FullName), ex); } } else { return(true); } return(false); }
/// <summary> /// Load the the new GRAMPS data. /// </summary> /// <returns> /// True if the load is successful or False if not. /// </returns> public async Task <bool> TriggerLoadGrampsUnZippedFolderAsync() { _commonNotifications.DataLogEntryAdd("Loading GRAMPS XML unzipped data"); { ClearRepositories(); bool tt = await _ExternalStorage.DataStorageLoadXML().ConfigureAwait(false); if (tt) { await _ExternalStorage.LoadXMLDataAsync().ConfigureAwait(false); _commonNotifications.DataLogEntryAdd("Finished loading GRAMPS XML data"); IFileInfoEx t = new FileInfoEx(argFileName: Common.Constants.StorageXMLFileName); if (t.Valid) { // Save the current Index File modified date for later checking CommonLocalSettings.SaveLastWriteToSettings(t, Common.Constants.SettingsXMLFileLastDateTimeModified); } UpdateSavedLocalSettings(); // save the data in a serial format for next time localEventAggregator.GetEvent<DataSaveSerialEvent>().Publish(null); // let everybody know we have finished loading data App.Current.Services.GetService <IMessenger>().Send(new DataLoadXMLEvent(true)); return(true); } } return(true); }
private ulong calc_size(FileInfoEx info) { var ret = 0UL; if (((options & CopyEngineOptions.CopyFilesRecursive) == CopyEngineOptions.CopyFilesRecursive) && (info.Directory)) { if ((destination_remote) || (((options & CopyEngineOptions.CopySymlinkAsSymlink) != CopyEngineOptions.CopySymlinkAsSymlink) || (info.LinkInformation == null))) { var dir_enum = new FileInfoExEnumerable (Path.Combine(info.FullName, "*"), true, true, true, true); foreach (var ch_info in dir_enum) { ret += calc_size(ch_info); } } } else { if (Wildcard.Match(initial_mask, info.FileName, false)) { ret += info.Size; } } return(ret); }
public static IPreviewHandler InitalizePreviewHandler(FileInfoEx file) { IPreviewHandler retVal = null; PreviewerInfo previewer = getPreviewer(file.FullName); if (previewer != null) { bool isInitialized = false; Type a = Type.GetTypeFromCLSID(previewer.CLSID, true); object o = Activator.CreateInstance(a); IInitializeWithFile fileInit = o as IInitializeWithFile; IInitializeWithStream streamInit = o as IInitializeWithStream; if (fileInit != null) { fileInit.Initialize(file.FullName, 0); isInitialized = true; } else if (streamInit != null) { FileStreamEx stream = file.OpenRead(); streamInit.Initialize((IStream)stream, 0); isInitialized = true; } if (isInitialized) retVal = o as IPreviewHandler; } return retVal; }
private void BackupFile(SyncItem SyncParent, FileInfoEx item, string sourceName) { try { string backupFile = System.IO.Path.Combine(SyncParent.BackupPath, item.FileName); VerifyPath(System.IO.Path.GetDirectoryName(backupFile)); string path = System.IO.Path.GetDirectoryName(backupFile); string baseFileName = System.IO.Path.GetFileNameWithoutExtension(backupFile); string fileExtension = System.IO.Path.GetExtension(backupFile); int counter = 0; bool backedUp = false; do { if (File.Exists(backupFile)) { counter++; string filename = string.Format("{0}({1:000}){2}", baseFileName, counter, fileExtension); backupFile = System.IO.Path.Combine(path, filename); } else { File.Copy(sourceName, backupFile); backedUp = true; } } while (!backedUp); } catch (Exception ex) { throw new Exception(string.Format("Exception while backing up the file '{0}' - {1}", item.FileName, ex.Message), ex); } }
/// <summary> /// Load the the new GRAMPS data. /// </summary> /// <returns> /// True if the load is successful or False if not. /// </returns> public async Task <bool> TriggerLoadGRAMPSFileAsync(bool deleteOld) { FileInfoEx fileGrampsDataInput = await StoreFolder.FolderGetFileAsync(DataStore.AD.CurrentDataFolder, CommonConstants.StorageGRAMPSFileName).ConfigureAwait(false); if (fileGrampsDataInput != null) { if (deleteOld) { // TODO fix this //await localStoreFile.DataStorageInitialiseAsync(DataStore.AD.CurrentDataFolder).ConfigureAwait(false); } await localStoreFile.DecompressGZIP(fileGrampsDataInput).ConfigureAwait(false); // Save the current Index File modified date for later checking //StoreFileNames.SaveFileModifiedSinceLastSave(CommonConstants.SettingsGPRAMPSFileLastDateTimeModified, CommonConstants.StorageGRAMPSFileName); StoreFileNames.SaveFileModifiedSinceLastSave(CommonConstants.SettingsGPRAMPSFileLastDateTimeModified, fileGrampsDataInput); } await DataStore.CN.MajorStatusDelete().ConfigureAwait(false); await DataStore.CN.ChangeLoadingMessage(null).ConfigureAwait(false); return(false); }
private void calc_size_count(FileInfoEx dir_info, ref long size, ref long allocation, ref long file_count, ref long dir_count) { FileInfoExEnumerable dir_enum = new FileInfoExEnumerable (Path.Combine(dir_info.FullName, "*"), true, true, true, true); foreach (FileInfoEx info in dir_enum) { IntPtr h_file = IntPtr.Zero; try { h_file = WinAPiFSwrapper.CreateFileHandle (info.FullName, Win32FileAccess.READ_ATTRIBUTES | Win32FileAccess.READ_EA, FileShare.ReadWrite | FileShare.Delete, FileMode.Open, info.Directory ? CreateFileOptions.BACKUP_SEMANTICS : CreateFileOptions.None); NT_FILE_STANDARD_INFORMATION s_info = ntApiFSwrapper.GetFileInfo_standard(h_file); size += s_info.EndOfFile; allocation += s_info.AllocationSize; //if (s_info.AllocationSize < s_info.EndOfFile) //{ // /*DEBUG*/ // long delta = s_info.EndOfFile - s_info.AllocationSize; //} } catch (Exception) { //Messages.ShowException // (ex, // string.Format // (Options.GetLiteral(Options.LANG_CANNOT_READ_ATTRIBUTES_0), // info.FullName)); break; } finally { if ((h_file.ToInt32() != WinApiFS.INVALID_HANDLE_VALUE) && (h_file != IntPtr.Zero)) { WinApiFS.CloseHandle(h_file); } } if (info.Directory) { calc_size_count(info, ref size, ref allocation, ref file_count, ref dir_count); dir_count++; } else { file_count++; } } }
public MusicInfo(FileInfoEx file) { UniqueId = Guid.NewGuid(); if (!file.Exists) { throw new FileNotFoundException("File not found: " + file.FullName); } FilePath = file.FullName; GetInfoFromTag(); }
public static Bitmap ExtractImage(FileInfoEx entry, Size size, bool quality) { try { IntPtr iExtractImagePtr = IntPtr.Zero; IExtractImage iExtractImage = null; if (GetIExtractImage(entry, out iExtractImagePtr, out iExtractImage)) { try { ShellDll.ShellAPI.SIZE prgSize = new ShellAPI.SIZE() { cx = size.Width, cy = size.Height }; IExtractImageFlags flags = IExtractImageFlags.Cache | IExtractImageFlags.Aspect; if (quality) { flags |= IExtractImageFlags.Quality; } StringBuilder location = new StringBuilder(260, 260); try { int pdwPriority = 1; iExtractImage.GetLocation(location, location.Capacity, ref pdwPriority, ref prgSize, 32, ref flags); } catch (COMException) { } IntPtr ptrBitmapImage = IntPtr.Zero; iExtractImage.Extract(out ptrBitmapImage); if (ptrBitmapImage != IntPtr.Zero) { return(Bitmap.FromHbitmap(ptrBitmapImage)); } } catch (Exception) { } } finally { if (iExtractImage != null) { Marshal.ReleaseComObject(iExtractImage); } if (iExtractImagePtr != IntPtr.Zero) { Marshal.Release(iExtractImagePtr); } } return(null); }
/// <summary> /// Opens the shell context menu instead of the normal context menu on right click. /// </summary> static void OnContextMenuOpening(object sender, ContextMenuEventArgs e) { Control control = sender as Control; // Attempt to open the explorer context menu for the application. If the file does not exist or // there is some other problem then a context menu (defined in the XAML) with just "Edit Entry" // and "Remove Entry" is opened instead. if (control != null && control.DataContext is ApplicationViewModel) { ApplicationViewModel application = (ApplicationViewModel)control.DataContext; if (File.Exists(application.FilePath)) { ContextMenuWrapper cmw = new ContextMenuWrapper(); cmw.OnQueryMenuItems += (QueryMenuItemsEventHandler) delegate(object s, QueryMenuItemsEventArgs args) { args.ExtraMenuItems = new string[] { "Edit Dock Entry", "Remove Dock Entry", "---" }; args.GrayedItems = new string[] { "delete", "rename", "cut", "copy" }; args.HiddenItems = new string[] { "link" }; args.DefaultItem = 1; }; cmw.OnAfterPopup += (AfterPopupEventHandler) delegate(object s, AfterPopupEventArgs args) { Messenger.Default.Send <ShellContextMenuMessage>(ShellContextMenuMessage.Closed()); }; Messenger.Default.Send <ShellContextMenuMessage>(ShellContextMenuMessage.Opened()); try { FileSystemInfoEx[] files = new[] { FileInfoEx.FromString(application.FilePath) }; int[] position = Win32Mouse.GetMousePosition(); string command = cmw.Popup(files, new System.Drawing.Point(position[0], position[1])); // Handle the click on the 'ExtraMenuItems'. switch (command) { case "Edit Dock Entry": Messenger.Default.Send <ApplicationMessage>(ApplicationMessage.Edit(application)); break; case "Remove Dock Entry": Messenger.Default.Send <ApplicationMessage>(ApplicationMessage.Remove(application)); break; } e.Handled = true; // Don't open the normal context menu. } catch (Exception ex) { Debug.Print("Problem displaying shell context menu: {0}", ex); } } } }
public static void AttachPreview(IntPtr handler, FileInfoEx file, Rectangle viewRect) { if (pHandler != null) { pHandler.Unload(); } string fileName = file.FullName; string CLSID = "8895b1c6-b41f-4c1c-a562-0d564250836f"; Guid g = new Guid(CLSID); string[] exts = fileName.Split('.'); string ext = exts[exts.Length - 1]; using (RegistryKey hk = Registry.ClassesRoot.OpenSubKey(string.Format(@".{0}\ShellEx\{1:B}", ext, g))) { if (hk != null) { g = new Guid(hk.GetValue("").ToString()); Type a = Type.GetTypeFromCLSID(g, true); object o = Activator.CreateInstance(a); IInitializeWithFile fileInit = o as IInitializeWithFile; IInitializeWithStream streamInit = o as IInitializeWithStream; bool isInitialized = false; if (fileInit != null) { fileInit.Initialize(fileName, 0); isInitialized = true; } else if (streamInit != null) { FileStreamEx stream = file.OpenRead(); //COMStream stream = new COMStream(File.Open(fileName, FileMode.Open)); streamInit.Initialize((IStream)streamInit, 0); isInitialized = true; } if (isInitialized) { pHandler = o as IPreviewHandler; if (pHandler != null) { ShellAPI.RECT r = new ShellAPI.RECT(viewRect); pHandler.SetWindow(handler, ref r); pHandler.SetRect(ref r); pHandler.DoPreview(); } } } } }
public IList <FileInfoEx> GetFileInfoWithLevel(string path, bool isContainHide = false) { FileInfoEx root = new FileInfoEx() { FileName = "Root", IsDirectory = true }; DirectoryInfo dire = new DirectoryInfo(path); root.ChildrenFileInfo = GetFileInfoWithLevel(dire, isContainHide); return(root.ChildrenFileInfo); }
public static object GetProperty(FileInfoEx file, PropertyKey propKey) { if (file.Exists) { using (ShellFolder2 sf2 = file.Parent.ShellFolder) { ShellDll.PropertyKey pkey = propKey; return(GetProperty(sf2, file, ref pkey)); } } return(null); }
public void SetInfo(FileInfoEx info) { lock (_lock) { Path = info.FullName; Filename = info.Name; Size = info.Length; CreationTime = info.CreationTime; LastAccessTime = info.LastAccessTime; LastWriteTime = info.LastWriteTime; } }
public static MusicInfo Create(FileInfoEx file, Action <Exception, string> errorCallback) { try { return(new MusicInfo(file)); } catch (Exception ex) { errorCallback(ex, file.FullName); return(null); } }
public virtual bool DeleteChildFile(FileInfoEx f) { foreach (var c in _children) { if (c.Path == f.FullName) { c.OnFileSystemEntryDeleted(); return(DeleteChild(c)); } } return(false); }
private FileExplorerEntry GetFileEntry(FileInfoEx fileInfo) { var result = new FileEntry { Name = fileInfo.Name, Size = fileInfo.Length, CreationTime = fileInfo.CreationTimeUtc, LastAccess = fileInfo.LastAccessTimeUtc }; return(result); }
/// this runs on a FileSystemWatcher thread public override BblLibraryNode OnFileSystemEntryRenamed(FileSystemInfoEx newInfo) { if (!_demoted && !IsBblBookDirectoryExtension(newInfo.Extension)) { Root.OnBookOperation(new BookOperationData(this, BookOperations.Remove, null)); Application.Current.Dispatcher.BeginInvokeIfRequired(DispatcherPriority.Normal, new Action(() => { FireDemoted(); })); _demoted = true; } else if (_demoted && IsBblBookDirectoryExtension(newInfo.Extension)) { Root.OnBookOperation(new BookOperationData(this, BookOperations.Add, null)); _demoted = false; } if (Children != null) { foreach (var c in Children) { string newPath = c.Path.Replace(Path, newInfo.FullName); if (c.IsFolder) { c.OnFileSystemEntryRenamed(new DirectoryInfoEx(newPath)); } else { c.OnFileSystemEntryRenamed(new FileInfoEx(newPath)); } } } String oldPath = Path; LoadInfo(newInfo); if (_pages != null) { var pArr = _pages.ToArray(); foreach (var p in pArr) { string newPath = p.Path.Replace(oldPath, newInfo.FullName); FileInfoEx info = new FileInfoEx(newPath); if (info.Exists) { p.SetInfo(info); } } } if (!_demoted) { Application.Current.Dispatcher.BeginInvokeIfRequired(DispatcherPriority.Normal, new Action(() => { FireRenamed(); })); } return(this); }
/// <summary> /// Loads the Gramps XML data. /// </summary> /// <param name="dataFolder"> /// StorageFolder to load. /// </param> /// <returns> /// Flag if Gramps Data Only loaded successfully. /// </returns> public async Task <bool> DataStorageLoadXML() { try { FileInfoEx inputFile = StoreFolder.FolderGetFile(DataStore.AD.CurrentDataFolder, CommonConstants.StorageXMLFileName); await DataStore.CN.MajorStatusAdd("Loading existing local copy of the GRAMPS data").ConfigureAwait(false); { Stream xmlReader = inputFile.FInfo.OpenRead(); try { // string t = inputFile.Path; localGrampsXMLdoc = XDocument.Load(xmlReader); } catch (Exception ex) { DataStore.CN.NotifyException("Can not load the Gramps XML file. Error in basic XML load", ex); throw; } int compareFlag = string.Compare(localGrampsXMLdoc.DocumentType.PublicId, CommonConstants.GrampsXMLPublicId, StringComparison.CurrentCulture); if (compareFlag < 0) { DataStore.CN.NotifyError("The program can only load files with a Gramps XML version of " + CommonConstants.GrampsXMLPublicId + " or greater. This file is version " + localGrampsXMLdoc.DocumentType.PublicId); return(false); } var nameSpaceList = localGrampsXMLdoc.Root.Attributes().Where( a => a.IsNamespaceDeclaration).GroupBy( a => a.Name.Namespace == XNamespace.None ? string.Empty : a.Name.LocalName, a => XNamespace.Get(a.Value)).ToDictionary( g => g.Key, g => g.FirstOrDefault()); ns = nameSpaceList.FirstOrDefault().Value.NamespaceName; xmlReader.Dispose(); } await DataStore.CN.MajorStatusDelete().ConfigureAwait(false); } catch (Exception ex) { DataStore.CN.NotifyException("trying to load Gramps data only", ex); throw; } return(true); }
private async void DownloadFileButton_OnClick(object sender, RoutedEventArgs e) { FileInfoEx fileInfoEx = FilesDataGrid.SelectedItem as FileInfoEx; if (fileInfoEx != null) { ProgressDialogController controller = await this.ShowProgressAsync("Загрузка файла", "Подождите идет загрузка файла на компьютер..."); controller.SetIndeterminate(); try { string directoryPath = ConfigurationSettings.AppSettings["DownloadFilesFolder"]; DirectoryInfo directoryInfo; if (!Directory.Exists(directoryPath)) { directoryInfo = Directory.CreateDirectory(directoryPath); } else { directoryInfo = new DirectoryInfo(directoryPath); } string filePath = Path.Combine(directoryInfo.FullName, fileInfoEx.OriginalFileName); using (FileTransferServiceClient client = new FileTransferServiceClient()) using (FileStream stream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None)) { FileDataDownload download; do { download = await client.DownloadAsync(fileInfoEx); if (download.Data != null) { stream.Write(download.Data, 0, download.Data.Length); } } while (!download.IsLastPart); } await this.ShowMessageAsync("Загрузка файла", "Файл был успешно загружен на компьютер!"); } catch (Exception exception) { await this.ShowMessageAsync("Ошибка", exception.Message); } await controller.CloseAsync(); } }
private List<FileInfoEx> ReadSourceFiles() { List<FileInfoEx> files = new List<FileInfoEx>(); FileSystemEnumerator enumerator = new FileSystemEnumerator(SourceDirectory, "*.*", true); foreach (FileInfo fi in enumerator.Matches()) { string file = fi.FullName; if ((IsIgnorable(file))) continue; FileInfoEx thisInfo = new FileInfoEx(file, SourceDirectory.Length); files.Add(thisInfo); } return files; }
public BblLibraryNode AddFile(string path) { FileInfoEx f = new FileInfoEx(path); var ext = f.Extension; BblLibraryNode parent = FindChild(f.Parent); if (parent != null) { var n = parent.AddChildFile(f); return(n); } return(null); }
private string ArchivePath(FileInfo file) { var dir = Target.Archive; if (dir.IsBlank()) { dir = file.Directory.CreateSubdirectory("archive").FullName; } Directory.CreateDirectory(dir); var path = Path.Combine(dir, file.Name); return(FileInfoEx.IncrementFileName(path)); }
public static bool GetIExtractImage( FileInfoEx file, out IntPtr iExtractImagePtr, out IExtractImage iExtractImage) { using (ShellFolder2 sf2 = file.Parent.ShellFolder) { PIDL filePIDL = file.PIDLRel; try { return(GetIExtractImage(sf2, filePIDL.Ptr, out iExtractImagePtr, out iExtractImage)); } finally { filePIDL.Free(); } } }
public bool GetPlaylistFiles(string path, out IEnumerable <string> entries) { try { var dir = new FileInfoEx(path).DirectoryName.TrimEnd('\\'); entries = new List <string>(from f in FileEx.ReadAllLines(path) where !string.IsNullOrWhiteSpace(f) && !f.StartsWith("#EXT") select f[1] == ':' || f.StartsWith("\\\\") ? f : (dir + "\\" + f)); return(true); } catch { entries = null; return(false); } }
/// <summary> /// 从指定目录搜索匹配指定名称的文件 /// </summary> /// <param name="name"></param> /// <param name="dire"></param> private void SearchFromDirectory(string name, DirectoryInfo dire, bool isSuffix) { FileInfo[] files; DirectoryInfo[] dires; try { if (isSuffix) { files = dire.GetFiles(string.Format("*.{0}", name)); } else { files = dire.GetFiles(string.Format("*{0}*.*", name)); //搜索文件格式 } dires = dire.GetDirectories(); } catch (Exception ex) { Loger.Log(Assembly.GetExecutingAssembly().FullName, MethodBase.GetCurrentMethod().FullName(), ex); return; } foreach (FileInfo n in files) { FileInfoEx file = new FileInfoEx { Attributes = n.Attributes, Length = n.Length, FullName = n.FullName, FileName = n.Name, LastAccessTime = n.LastAccessTime }; SearchResult.Add(file); } if (dires.Count() == 0) { return; } foreach (var item in dires) { SearchFromDirectory(name, item, isSuffix); } }
public static Bitmap ExtractImage(FileInfoEx entry, Size size, bool quality) { try { IntPtr iExtractImagePtr = IntPtr.Zero; IExtractImage iExtractImage = null; if (GetIExtractImage(entry, out iExtractImagePtr, out iExtractImage)) try { ShellDll.ShellAPI.SIZE prgSize = new ShellAPI.SIZE() { cx = size.Width, cy = size.Height }; IExtractImageFlags flags = IExtractImageFlags.Cache | IExtractImageFlags.Aspect; if (quality) flags |= IExtractImageFlags.Quality; StringBuilder location = new StringBuilder(260, 260); try { int pdwPriority = 1; iExtractImage.GetLocation(location, location.Capacity, ref pdwPriority, ref prgSize, 32, ref flags); } catch (COMException) { } IntPtr ptrBitmapImage = IntPtr.Zero; iExtractImage.Extract(out ptrBitmapImage); if (ptrBitmapImage != IntPtr.Zero) return Bitmap.FromHbitmap(ptrBitmapImage); } catch (Exception) { } finally { if (iExtractImage != null) Marshal.ReleaseComObject(iExtractImage); if (iExtractImagePtr != IntPtr.Zero) Marshal.Release(iExtractImagePtr); } return null; } catch (NotSupportedException) { return null; } }
public PreviewerControl(FileInfoEx file) { _file = file; }
private void ReadFiles() { if (string.IsNullOrEmpty(txtOutputFolder.Text.Trim()) || !Directory.Exists(txtOutputFolder.Text.Trim())) return; lstFiles.BeginUpdate(); lstFiles.Items.Clear(); string outputDir = txtOutputFolder.Text.Trim(); int outputDirLength = txtOutputFolder.Text.Trim().Length; FileSystemEnumerator enumerator = new FileSystemEnumerator(txtOutputFolder.Text.Trim(), "*.*", true); foreach (FileInfo fi in enumerator.Matches()) { string thisFile = fi.FullName; if ((IsIgnorable(thisFile))) continue; FileInfoEx thisInfo = new FileInfoEx(thisFile,outputDirLength); ListViewItem thisItem = new ListViewItem(thisInfo.RelativeName, GetImageIndex(thisInfo.FileInfo.Extension)); thisItem.SubItems.Add(thisInfo.FileVersion); thisItem.SubItems.Add(thisInfo.FileInfo.Length.ToString(CultureInfo.InvariantCulture)); thisItem.SubItems.Add(thisInfo.FileInfo.LastWriteTime.ToString(CultureInfo.InvariantCulture)); thisItem.SubItems.Add(thisInfo.Hash); thisItem.Checked = (!Settings.Default.IgnoreFiles.Contains(thisInfo.FileInfo.Name)); thisItem.Tag = thisInfo; lstFiles.Items.Add(thisItem); } lstFiles.EndUpdate(); }
public static bool GetIExtractImage( FileInfoEx file, out IntPtr iExtractImagePtr, out IExtractImage iExtractImage) { using (ShellFolder2 sf2 = file.Parent.ShellFolder) { PIDL filePIDL = file.PIDLRel; try { return GetIExtractImage(sf2, filePIDL.Ptr, out iExtractImagePtr, out iExtractImage); } finally { filePIDL.Free(); } } }
public static bool Support(FileInfoEx file) { return Support(file.Name); }
void CopyFile(FileInfoEx item, DirectoryInfoEx destDir) { FileSystemInfoEx lookupItem = destDir[item.Name]; if (lookupItem is FileInfoEx) { if (item.Length == (lookupItem as FileInfoEx).Length) { string srcCRC = Helper.GetFileCRC(item.FullName); string destCRC = Helper.GetFileCRC(lookupItem.FullName); if (srcCRC == destCRC && item.Length == (lookupItem as FileInfoEx).Length) return; //Same file, no copy needed. } } OverwriteMode overwrite = OverwriteMode.Replace; if (lookupItem != null) overwrite = AskOverwrite(item, lookupItem); switch (overwrite) { case OverwriteMode.Replace : if (lookupItem != null) lookupItem.Delete(); FileCancelDelegate cancel = delegate { return Aborted; }; IOTools.CopyFile(item.FullName, PathEx.Combine(destDir.FullName, item.Name), cancel); break; } }
private void ReadFiles() { if (!string.IsNullOrEmpty(txtOutputFolder.Text.Trim()) && Directory.Exists(txtOutputFolder.Text.Trim())) { ListViewItem thisItem = null; FileInfoEx thisInfo = null; lstFiles.BeginUpdate(); lstFiles.Items.Clear(); var enumerator = new FindFiles.FileSystemEnumerator(txtOutputFolder.Text.Trim(),"*.*", true); foreach (FileInfo fi in enumerator.Matches()) { string thisFile = fi.FullName; if ((!IsIgnorable(thisFile))) { thisInfo = new FileInfoEx(thisFile); var _with4 = thisInfo; thisItem = new ListViewItem(_with4.FileInfo.Name, GetImageIndex(_with4.FileInfo.Extension)); thisItem.SubItems.Add(_with4.FileVersion); thisItem.SubItems.Add(_with4.FileInfo.Length.ToString()); thisItem.SubItems.Add(_with4.FileInfo.LastWriteTime.ToString()); thisItem.SubItems.Add(_with4.Hash); thisItem.Checked = (!Settings.Default.IgnoreFiles.Contains(_with4.FileInfo.Name)); thisItem.Tag = thisInfo; lstFiles.Items.Add(thisItem); } } lstFiles.EndUpdate(); } }
private void ReadFiles() { string outputDir = txtOutputFolder.Text.Trim(); if (string.IsNullOrEmpty(outputDir) || !Directory.Exists(outputDir)) { return; } if (!outputDir.EndsWith("\\")) { outputDir += "\\"; } lstFiles.BeginUpdate(); lstFiles.Items.Clear(); foreach (string path in Directory.GetFiles(outputDir, "*.*", SearchOption.AllDirectories)) { var fi = new FileInfo(path); var outputDI = new DirectoryInfo(outputDir); string filePath = fi.FullName; FileInfoEx fileInfo = new FileInfoEx(filePath, outputDI.FullName.Length); if ((IsIgnorable(filePath) || IsIgnorableFile(fileInfo.RelativeName))) { continue; } ListViewItem item = new ListViewItem(fileInfo.RelativeName, GetImageIndex(fileInfo.FileInfo.Extension)); item.SubItems.Add(fileInfo.FileVersion); item.SubItems.Add(fileInfo.FileInfo.Length.ToString(CultureInfo.InvariantCulture)); item.SubItems.Add(fileInfo.FileInfo.LastWriteTime.ToString(CultureInfo.InvariantCulture)); item.SubItems.Add(fileInfo.Hash); //item.Checked = (!Settings.Default.IgnoreFiles.Contains(fileInfo.FileInfo.Name)); //item.Checked = !IsIgnorableFile(fileInfo.RelativeName); item.Tag = fileInfo; lstFiles.Items.Add(item); } lstFiles.EndUpdate(); }
public static object GetProperty(ShellFolder2 sf2, FileInfoEx file, ref PropertyKey propKey) { PIDL pidlLookup = file.PIDLRel; if (pidlLookup != null) { try { object retVal; int hr = sf2.GetDetailsEx(pidlLookup.Ptr, ref propKey, out retVal); if (hr != ShellAPI.S_OK) Marshal.ThrowExceptionForHR(hr); return retVal; } finally { pidlLookup.Free(); } } return null; }
public static object GetProperty(FileInfoEx file, PropertyKey propKey) { if (file.Exists) using (ShellFolder2 sf2 = file.Parent.ShellFolder) { ShellDll.PropertyKey pkey = propKey; return GetProperty(sf2, file, ref pkey); } return null; }
private void ReadFiles() { string outputDir = txtOutputFolder.Text.Trim(); if (string.IsNullOrEmpty(outputDir) || !Directory.Exists(outputDir)) { return; } if (!outputDir.EndsWith("\\")) { outputDir += "\\"; } lstFiles.BeginUpdate(); lstFiles.Items.Clear(); FileSystemEnumerator enumerator = new FileSystemEnumerator(outputDir, "*.*", true); foreach (FileInfo fi in enumerator.Matches()) { string filePath = fi.FullName; if ((IsIgnorable(filePath))) { continue; } FileInfoEx fileInfo = new FileInfoEx(filePath, outputDir.Length); ListViewItem item = new ListViewItem(fileInfo.RelativeName, GetImageIndex(fileInfo.FileInfo.Extension)); item.SubItems.Add(fileInfo.FileVersion); item.SubItems.Add(fileInfo.FileInfo.Length.ToString(CultureInfo.InvariantCulture)); item.SubItems.Add(fileInfo.FileInfo.LastWriteTime.ToString(CultureInfo.InvariantCulture)); item.SubItems.Add(fileInfo.Hash); item.Checked = (!Settings.Default.IgnoreFiles.Contains(fileInfo.FileInfo.Name)); item.Tag = fileInfo; lstFiles.Items.Add(item); } lstFiles.EndUpdate(); }
void MoveFile(FileInfoEx item, DirectoryInfoEx destDir) { FileSystemInfoEx lookupItem = destDir[item.Name]; OverwriteMode overwrite = OverwriteMode.Replace; if (lookupItem != null) overwrite = AskOverwrite(item, lookupItem); switch (overwrite) { case OverwriteMode.Replace: if (lookupItem != null) lookupItem.Delete(); IOTools.Move(item.FullName, PathEx.Combine(destDir.FullName, item.Name)); break; } }