public static void SendToTrash(string path) { SHFILEOPSTRUCT fileop = new SHFILEOPSTRUCT(); fileop.wFunc = FO_DELETE; fileop.pFrom = path + '\0' + '\0'; fileop.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION; SHFileOperation(ref fileop); }
public static bool CopyFiles(String from, String to) { SHFILEOPSTRUCT op = new SHFILEOPSTRUCT(); op.wFunc = FO_Func.FO_COPY; op.fFlags = (ushort)FO_Func.FOF_ALLOWUNDO; op.pFrom = from; op.pTo = to; return (SHFileOperation(ref op) == 0 && !op.fAnyOperationsAborted); }
public static int deleteFileOrFolder2Bin(string ff) { if (ff.EndsWith("\\")) ff = ff.Remove(ff.Length - 1, 1); SHFILEOPSTRUCT shf = new SHFILEOPSTRUCT(); shf.wFunc = FO_DELETE; shf.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION; shf.pFrom = ff + '\0' + '\0'; return SHFileOperation(ref shf); }
/// <summary> /// Verschiebt eine Datei in den Papierkorb /// </summary> /// <param name="filePath"></param> private static void DateiInPapierkorb(string filePath) { var fileop = new SHFILEOPSTRUCT { wFunc = FO_DELETE, pFrom = (filePath + '\0' + '\0'), fFlags = (FOF_ALLOWUNDO | FOF_NOCONFIRMATION) }; SHFileOperation(ref fileop); }
private static void DeleteFileOperation(string filePath) { var fileop = new SHFILEOPSTRUCT { wFunc = FoDelete, pFrom = filePath + '\0' + '\0', fFlags = FofAllowundo | FofNoconfirmation }; SHFileOperation(ref fileop); }
public static void DeleteFileToRecycleBin(string filename) { SHFILEOPSTRUCT shf = new SHFILEOPSTRUCT(); shf.wFunc = FO_DELETE; shf.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION; shf.pFrom = filename + "\0"; int result = SHFileOperation(ref shf); if (result != 0) Utilities.DebugLine("error: {0} while moving file {1} to recycle bin", result, filename); }
public static bool CallSH(FileOperationType type, string[] from, string to, FileOperationFlags flags) { var fs = new SHFILEOPSTRUCT(); fs.wFunc = type; if (from.Length > 0) fs.pFrom = string.Join("\0", from) + "\0\0"; if (to.Length > 0) fs.pTo = to + "\0\0"; fs.fFlags = flags; return SHFileOperation(ref fs) == 0; }
private static bool DeleteFile(string[] path, FileOperationFlags flags) { if (path == null || path.All(x => x == null)) return false; try { var fs = new SHFILEOPSTRUCT { wFunc = FileOperationType.FO_DELETE, pFrom = string.Join("\0", path.Where(x => x != null)) + "\0\0", fFlags = flags }; SHFileOperation(ref fs); return true; } catch (Exception) { return false; } }
/// <summary> /// Recursively deletes a directory using the shell API which can /// handle long file names /// </summary> /// <param name="dir"></param> public static void RecursivelyDeleteDirectory(string dir, bool silent = false) { SHFILEOPSTRUCT fileOp = new SHFILEOPSTRUCT(); fileOp.pFrom = dir + '\0'; // pFrom must be double null terminated fileOp.wFunc = FO_Func.FO_DELETE; fileOp.fFlags = FILEOP_FLAGS_ENUM.FOF_NOCONFIRMATION | FILEOP_FLAGS_ENUM.FOF_NOERRORUI; if (silent) { fileOp.fFlags |= FILEOP_FLAGS_ENUM.FOF_SILENT; } int res = SHFileOperation(ref fileOp); if (res != 0) { throw new IOException("Failed to delete dir " + res); } }
public static void DeleteToRecycleBin(string fileName) { if (!File.Exists(fileName) && !Directory.Exists(fileName)) throw new FileNotFoundException("File not found.", fileName); SHFILEOPSTRUCT info = new SHFILEOPSTRUCT(); info.hwnd = Gui.WorkbenchSingleton.MainWin32Window.Handle; info.wFunc = FO_FUNC.FO_DELETE; info.fFlags = FILEOP_FLAGS.FOF_ALLOWUNDO | FILEOP_FLAGS.FOF_NOCONFIRMATION; info.lpszProgressTitle = "Delete " + Path.GetFileName(fileName); info.pFrom = fileName + "\0"; // pFrom is double-null-terminated int result = SHFileOperation(ref info); if (result != 0) throw new IOException("Could not delete file " + fileName + ". Error " + result, result); }
/// <summary> /// Delete a file or directory by moving it to the trash bin /// </summary> /// <param name="filePath">Full path of the file.</param> /// <returns><c>true</c> if successfully deleted.</returns> public static bool DeleteToRecycleBin(string filePath) { if (PlatformUtilities.Platform.IsWindows) { if (!File.Exists(filePath) && !Directory.Exists(filePath)) return false; // alternative using visual basic dll: // FileSystem.DeleteDirectory(item.FolderPath,UIOption.OnlyErrorDialogs), RecycleOption.SendToRecycleBin); //moves it to the recyle bin var shf = new SHFILEOPSTRUCT(); shf.wFunc = FO_DELETE; shf.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION; string pathWith2Nulls = filePath + "\0\0"; shf.pFrom = pathWith2Nulls; SHFileOperation(ref shf); return !shf.fAnyOperationsAborted; } // On Linux we'll have to move the file to $XDG_DATA_HOME/Trash/files and create // a filename.trashinfo file in $XDG_DATA_HOME/Trash/info that contains the original // filepath and the deletion date. See http://stackoverflow.com/a/20255190 // and http://freedesktop.org/wiki/Specifications/trash-spec/. // Environment.SpecialFolder.LocalApplicationData corresponds to $XDG_DATA_HOME. // move file or directory if (Directory.Exists(filePath) || File.Exists(filePath)) { var trashPath = Path.Combine(Environment.GetFolderPath( Environment.SpecialFolder.LocalApplicationData), "Trash"); var trashedFileName = Path.GetRandomFileName(); if (!Directory.Exists(trashPath)) { // in case the trash bin doesn't exist we create it. This can happen e.g. // on the build machine Directory.CreateDirectory(Path.Combine(trashPath, "files")); Directory.CreateDirectory(Path.Combine(trashPath, "info")); } var recyclePath = Path.Combine(Path.Combine(trashPath, "files"), trashedFileName); WriteTrashInfoFile(trashPath, filePath, trashedFileName); // Directory.Move works for directories and files DirectoryUtilities.MoveDirectorySafely(filePath, recyclePath); return true; } return false; }
public static void DeleteFileOrFolder(string path) { try { SHFILEOPSTRUCT fileop = new SHFILEOPSTRUCT(); fileop.wFunc = FO_DELETE; fileop.pFrom = path + '\0' + '\0'; fileop.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION; SHFileOperation(ref fileop); } catch(Exception ex) { throw new ID3SQLException("Recycle option not available on this system", ex); } }
public static void DeleteToRecycleBin(string fileName, bool showConfirmation) { SHFILEOPSTRUCT shf = new SHFILEOPSTRUCT(); shf.hwnd = IntPtr.Zero; shf.wFunc = FO_Func.FO_DELETE; if (showConfirmation) { shf.fFlags = FOF_ALLOWUNDO; } else { shf.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION; } shf.pFrom = fileName + '\0'; SHFileOperation(ref shf); }
private static bool DeleteFile(string path, FileOperationFlags flags) { try { SHFILEOPSTRUCT fileOp = new SHFILEOPSTRUCT { wFunc = FileOperationType.FO_DELETE, pFrom = path + '\0' + '\0', fFlags = flags }; SHFileOperation(ref fileOp); return true; } catch (Exception) { return false; } }
private static bool Send(string path, FileOperationFlags flags) { try { SHFILEOPSTRUCT fileOp = new SHFILEOPSTRUCT { wFunc = FileOperationType.FO_DELETE, pFrom = path + '\0' + '\0', fFlags = (FileOperationFlags)((ushort)(FileOperationFlags.FOF_ALLOWUNDO | flags)) }; SHFileOperation(ref fileOp); return(true); } catch (Exception) { return(false); } }
public static void DeleteToRecycleBin(string fileName, bool showConfirmation) { SHFILEOPSTRUCT shf = new SHFILEOPSTRUCT(); shf.hwnd = IntPtr.Zero; shf.wFunc = FO_Func.FO_DELETE; if (showConfirmation) { shf.fFlags = FOF_ALLOWUNDO; } else { shf.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION; } shf.pFrom = fileName + '\0'; SHFileOperation(ref shf); }
/// <summary> /// Send file to recycle bin /// </summary> /// <param name="path">Location of directory or file to recycle</param> /// <param name="flags">FileOperationFlags to add in addition to FOF_ALLOWUNDO</param> public static bool Send(string path, FileOperationFlags flags) { try { var fs = new SHFILEOPSTRUCT { wFunc = FileOperationType.FO_DELETE, pFrom = path + '\0' + '\0', fFlags = FileOperationFlags.FOF_ALLOWUNDO | flags }; SHFileOperation(ref fs); return(true); } catch (Exception) { return(false); } }
public static bool CopyItems(List<string> items, string destination) { try { var fs = new SHFILEOPSTRUCT { wFunc = FileOperationType.FO_COPY, pFrom = string.Join("\0", items.ToArray()) + '\0' + '\0', pTo = destination + '\0' + '\0' }; SHFileOperation(ref fs); return true; } catch (Exception) { return false; } }
public static bool Perform(string path, FileOperationFlags flags) { try { var fs = new SHFILEOPSTRUCT { wFunc = FileOperationType.FO_DELETE, pFrom = path + '\0' + '\0', fFlags = FileOperationFlags.FOF_ALLOWUNDO | flags }; SHFileOperation(ref fs); return true; } catch (Exception) { return false; } }
public static bool MoveItems(List <string> items, string destination) { try { var fs = new SHFILEOPSTRUCT { wFunc = FileOperationType.FO_MOVE, pFrom = string.Join("\0", items.ToArray()) + '\0' + '\0', pTo = destination + '\0' + '\0' }; SHFileOperation(ref fs); return(true); } catch (Exception) { return(false); } }
private static bool deleteFile(string path, FileOperationFlags flags) { try { var fs = new SHFILEOPSTRUCT { wFunc = FileOperationType.FO_DELETE, pFrom = path + '\0' + '\0', fFlags = flags }; SHFileOperation(ref fs); return(true); } catch (Exception) { return(false); } }
// Main overload for standard Move\Copy file(s) operation private static bool DoFileOperation(FileOperationType foType, string[] files, string destination) { try { var fs = new SHFILEOPSTRUCT { wFunc = foType, pFrom = string.Join("\0", files) + '\0' + '\0', pTo = destination + '\0' + '\0' }; SHFileOperation(ref fs); return(true); } catch (Exception) { return(false); } }
public static bool MoveItems(List <string> items, string destination) { try { var fs = new SHFILEOPSTRUCT { wFunc = FileOperationType.FO_MOVE, pFrom = string.Join("\0", items.ToArray()) + '\0' + '\0', pTo = destination + '\0' + '\0' }; // tbener 3/2018 - changed to return False if cancelled by user return(SHFileOperation(ref fs) == 0); } catch (Exception) { // tbener 3/2018 - change from return false (as opposed to cancel) throw; } }
public static void DeleteToRecycleBin(string fileName) { if (!File.Exists(fileName) && !Directory.Exists(fileName)) { throw new FileNotFoundException("File not found.", fileName); } SHFILEOPSTRUCT info = new SHFILEOPSTRUCT(); info.wFunc = FO_FUNC.FO_DELETE; info.fFlags = FILEOP_FLAGS.FOF_ALLOWUNDO | FILEOP_FLAGS.FOF_NOCONFIRMATION; info.lpszProgressTitle = "Delete " + Path.GetFileName(fileName); info.pFrom = fileName + "\0"; // pFrom is double-null-terminated int result = SHFileOperation(ref info); if (result != 0) { throw new IOException("Could not delete file " + fileName + ". Error " + result, result); } }
/// <summary> /// Send file to recycle bin. /// Returns true on success. /// </summary> /// <param name="path">Location of directory or file to recycle</param> /// <param name="flags">FileOperationFlags to add in addition to FOF_ALLOWUNDO</param> public static bool Send(string path, FileOperationFlags flags) { // TODO find out what this does if recycle bin is disabled try { var fs = new SHFILEOPSTRUCT { wFunc = FileOperationType.FO_DELETE, pFrom = path + '\0' + '\0', fFlags = FileOperationFlags.FOF_ALLOWUNDO | flags }; int error = SHFileOperation(ref fs); return(error == 0); } catch (Exception) { return(false); } }
/// <summary> /// Send file to recycle bin /// </summary> /// <param name="path">Location of directory or file to recycle</param> /// <param name="flags">FileOperationFlags to add in addition to FOF_ALLOWUNDO</param> public static bool Send(string path, FileOperationFlags flags) { try { var fs = new SHFILEOPSTRUCT { wFunc = FileOperationType.FO_DELETE, pFrom = path + '\0' + '\0', fFlags = FileOperationFlags.FOF_ALLOWUNDO | flags }; SHFileOperation(ref fs); return(true); } catch (Exception e) { Debug.WriteLine("Deletion error: " + path + " " + e.Message); return(false); } }
private static bool DeleteFile(string[] path, FileOperationFlags flags) { path = path?.Where(Exists).ToArray(); if (path == null || path.Length == 0 || path.All(x => x == null)) { return(false); } try { var fs = new SHFILEOPSTRUCT { wFunc = FileOperationType.FO_DELETE, pFrom = string.Join("\0", path.Where(x => x != null)) + "\0\0", fFlags = flags }; SHFileOperation(ref fs); return(true); } catch (Exception) { return(false); } }
static bool DeleteFileOrFolder(string path, bool confirm = false) { SHFILEOPSTRUCT fileop = new SHFILEOPSTRUCT(); fileop.wFunc = FO_DELETE; fileop.pFrom = path + '\0' + '\0'; if (confirm) { fileop.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION; } else { fileop.fFlags = FOF_ALLOWUNDO; } var rc = SHFileOperation(ref fileop); return(rc == 0); }
/// <summary> /// Recursively deletes a directory using the shell API which can /// handle long file names /// </summary> /// <param name="dir"></param> public static void RecursivelyDeleteDirectory(string dir, bool silent = false) { SHFILEOPSTRUCT fileOp = new SHFILEOPSTRUCT(); fileOp.pFrom = dir + '\0'; // pFrom must be double null terminated fileOp.wFunc = FO_Func.FO_DELETE; fileOp.fFlags = FILEOP_FLAGS_ENUM.FOF_NOCONFIRMATION | FILEOP_FLAGS_ENUM.FOF_NOERRORUI; if (silent) { fileOp.fFlags |= FILEOP_FLAGS_ENUM.FOF_SILENT; } int res = SHFileOperation(ref fileOp); if (res != 0) { throw new System.IO.IOException("Failed to delete dir " + res); } }
/// <summary> /// Uses the Window Shell UI to move files which behaves similar to Explorer behavior /// warning for errors and supports undo. /// </summary> /// <param name="sourceFolder">Source file (or files via wildcard) or folder name</param> /// <param name="targetFolder">Target Folder</param> /// <param name="confirmation">If true prompts for overwrites</param> /// <returns>true or false</returns> public static bool MoveFileOrFolder(string sourceFolder, string targetFolder, bool confirmation = false) { var shf = new SHFILEOPSTRUCT(); shf.wFunc = FO_MOVE; if (confirmation) { shf.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION; } else { shf.fFlags = FOF_ALLOWUNDO; } shf.pFrom = sourceFolder + '\0'; // required! shf.pTo = targetFolder + '\0'; int result = SHFileOperation(ref shf); return(result == 0); }
/// <summary> /// Send file to recycle bin /// </summary> /// <param name="path">Location of directory or file to recycle</param> /// <param name="flags">FileOperationFlags to add in addition to FOF_ALLOWUNDO</param> public static bool Send(string path, FileOperationFlags flags) { try { var fs = new SHFILEOPSTRUCT { wFunc = FileOperationType.FO_DELETE, pFrom = path + '\0' + '\0', fFlags = FileOperationFlags.FOF_ALLOWUNDO | flags }; SHFileOperation(ref fs); return(true); } catch (Exception e) { MessageBox.Show(e.Message + Environment.NewLine + Environment.NewLine + e.StackTrace, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } return(false); }
/// <summary> /// Wrapper for extern method CreateSymbolicLink. This handles some error cases and provides better information /// in error cases. /// </summary> /// <param name="symlinkPath">Path to the symbolic link you wish to create.</param> /// <param name="targetPath">Path to the file/directory that the symbolic link should be pointing to.</param> public static void CreateSymbolicLink(string symlinkPath, string targetPath) { // Pre-checks. if (!(new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator))) { throw new UnauthorizedAccessException("Process must be run in elevated permissions in order to create symbolic link."); } else if (Directory.Exists(symlinkPath) || File.Exists(symlinkPath)) { throw new IOException("Path Already Exists. We cannot create a symbolic link here"); } // Create the correct symbolic link. bool result; if (SHFILEOPSTRUCT.Exists(targetPath)) { result = CreateSymbolicLink(symlinkPath, targetPath, NativeMethods.SymbolicLink.File); } else if (Directory.Exists(targetPath)) { result = CreateSymbolicLink(symlinkPath, targetPath, NativeMethods.SymbolicLink.Directory); } else { throw new FileNotFoundException("Target File/Directory was not found. Cannot make a symbolic link."); } // Validate that we created a symbolic link. // If we failed and the symlink doesn't exist throw an exception here. if (!result) { if (!Directory.Exists(symlinkPath) && !File.Exists(symlinkPath)) { throw new FileNotFoundException("Unable to find symbolic link after creation."); } else { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } } }
public bool DeleteDirectory(string strDir) { if (!Directory.Exists(strDir)) { return(false); } Stopwatch sw = new Stopwatch(); string[] rgstrFiles = Directory.GetFiles(strDir); sw.Start(); for (int i = 0; i < rgstrFiles.Length; i++) { SHFILEOPSTRUCT shf = new SHFILEOPSTRUCT(); shf.wFunc = FO_DELETE; shf.fFlags = FOF_ALLOWUNDO + FOF_NOCONFIRMATION; shf.pFrom = strDir + '\0' + '\0'; SHFileOperation(ref shf); if (m_evtCancel.WaitOne(0)) { return(false); } if (sw.Elapsed.TotalMilliseconds > 1000) { m_log.Progress = (double)i / (double)rgstrFiles.Length; m_log.WriteLine("deleting " + i.ToString("N0") + " of " + rgstrFiles.Length.ToString("N0") + "..."); sw.Restart(); } } rgstrFiles = Directory.GetFiles(strDir); if (rgstrFiles.Length == 0) { Directory.Delete(strDir); } return(true); }
/// <summary> /// 删除单个或多个文件 /// </summary> /// <param name="fileName">删除的文件名,如果是多个文件,文件名之间以字符串结尾符'\0'隔开</param> /// <param name="toRecycle">指示是将文件放入回收站还是永久删除,true-放入回收站,false-永久删除</param> /// <param name="showDialog">指示是否显示确认对话框,true-显示确认删除对话框,false-不显示确认删除对话框</param> /// <param name="showProgress">指示是否显示进度对话框,true-显示,false-不显示。该参数当指定永久删除文件时有效</param> /// <param name="errorMsg">反馈错误消息的字符串</param> /// <returns>操作执行结果标识,删除文件成功返回0,否则,返回错误代码</returns> private static int ToDelete(string fileName, bool toRecycle, bool showDialog, bool showProgress, ref string errorMsg) { SHFILEOPSTRUCT lpFileOp = new SHFILEOPSTRUCT(); lpFileOp.wFunc = wFunc.FO_DELETE; lpFileOp.pFrom = fileName + "\0"; //将文件名以结尾字符"\0"结束 lpFileOp.fFlags = FILEOP_FLAGS.FOF_NOERRORUI; if (toRecycle) { lpFileOp.fFlags |= FILEOP_FLAGS.FOF_ALLOWUNDO; //设定删除到回收站 } if (!showDialog) { lpFileOp.fFlags |= FILEOP_FLAGS.FOF_NOCONFIRMATION; //设定不显示提示对话框 } if (!showProgress) { lpFileOp.fFlags |= FILEOP_FLAGS.FOF_SILENT; //设定不显示进度对话框 } lpFileOp.fAnyOperationsAborted = true; int n = SHFileOperation(ref lpFileOp); if (n == 0) { return(0); } string tmp = GetErrorString(n); //.av 文件正常删除了但也提示 402 错误,不知道为什么。屏蔽之。 if ((fileName.ToLower().EndsWith(".av") && n.ToString("X") == "402")) { return(0); } errorMsg = string.Format("{0}({1})", tmp, fileName); return(n); }
public static void Compress(string folderPath, string fileName) { try { string extension = ".zip"; string file = folderPath + @"\" + fileName; fileName = (fileName + extension).Replace(".bak", ""); Thread thread = new Thread(t => { using (ZipFile zip = new ZipFile()) { zip.Password = "******"; zip.CompressionLevel = CompressionLevel.BestCompression; FileInfo fileInfo = new FileInfo(fileName); zip.AddFile(file, ""); DirectoryInfo di = new DirectoryInfo(file); folderPath = string.Format(@"{0}\{1}", di.Parent.FullName, fileInfo.Name); zip.Save(folderPath); File.Delete(file); var shf = new SHFILEOPSTRUCT(); shf.wFunc = FO_DELETE; shf.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION; shf.pFrom = file; SHFileOperation(ref shf); Console.WriteLine("Compress completed."); } }); thread.Start(); } catch (Exception ex) { Console.WriteLine("Compress completed."); Console.WriteLine(ex.Message); } }
/// <summary> /// Actually do the move of a file/directory to the recycleBin /// </summary> /// <param name="path"></param> /// <returns>true if it succeed.</returns> public static bool Recycle(string path) { try { #if MONO // TODO: Find a way in Mono to send something to the recycle bin. try { File.Delete(path); } catch { try { Directory.Delete(path); } catch { } } return(true); #else //alternative using visual basic dll: FileSystem.DeleteDirectory(item.FolderPath,UIOption.OnlyErrorDialogs), RecycleOption.SendToRecycleBin); //moves it to the recyle bin var shf = new SHFILEOPSTRUCT(); shf.wFunc = FO_DELETE; shf.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION; string pathWith2Nulls = path + "\0\0"; shf.pFrom = pathWith2Nulls; SHFileOperation(ref shf); return(!shf.fAnyOperationsAborted); #endif } catch (Exception exception) { Palaso.Reporting.ErrorReport.NotifyUserOfProblem(exception, "Could not delete that book."); return(false); } }
public static void DeleteFile(string filepath) { if (!File.Exists(filepath)) { return; } ThreadStart ts = new ThreadStart(() => { SHFILEOPSTRUCT shf = new SHFILEOPSTRUCT(); shf.wFunc = FO_DELETE; shf.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION; shf.pFrom = filepath; SHFileOperation(ref shf); }); Thread t = new Thread(ts); t.Start(); }
public static void DeleteToRecycleBin(string fileName) { if (!File.Exists(fileName) && !Directory.Exists(fileName)) { throw new FileNotFoundException("File not found.", fileName); } var info = new SHFILEOPSTRUCT { hwnd = Altaxo.Current.Gui.MainWindowHandle, wFunc = FO_FUNC.FO_DELETE, fFlags = FILEOP_FLAGS.FOF_ALLOWUNDO | FILEOP_FLAGS.FOF_NOCONFIRMATION, lpszProgressTitle = "Delete " + Path.GetFileName(fileName), pFrom = fileName + "\0" // pFrom is double-null-terminated }; int result = SHFileOperation(ref info); if (result != 0) { throw new IOException("Could not delete file " + fileName + ". Error " + result, result); } }
// Effective Function public static int SHFileOperation(SHFILEOPSTRUCT lpFileOp) { if (!Is64Bit()) { return(SHFileOperation32(lpFileOp)); } var shfileopstruct1 = new SHFILEOPSTRUCT64(); shfileopstruct1.hwnd = lpFileOp.hwnd; shfileopstruct1.wFunc = lpFileOp.wFunc; shfileopstruct1.pFrom = lpFileOp.pFrom; shfileopstruct1.pTo = lpFileOp.pTo; shfileopstruct1.fFlags = lpFileOp.fFlags; shfileopstruct1.fAnyOperationsAborted = lpFileOp.fAnyOperationsAborted; shfileopstruct1.hNameMappings = lpFileOp.hNameMappings; shfileopstruct1.lpszProgressTitle = lpFileOp.lpszProgressTitle; var ret = SHFileOperation64(shfileopstruct1); lpFileOp.fAnyOperationsAborted = shfileopstruct1.fAnyOperationsAborted; return(ret); }
static int SHFileOperation(ref SHFILEOPSTRUCT lpFileOp) { if (IntPtr.Size == 4) { return(SHFileOperation32(ref lpFileOp)); } SHFILEOPSTRUCT64 shfileopstruct = new SHFILEOPSTRUCT64(); shfileopstruct.hwnd = lpFileOp.hwnd; shfileopstruct.wFunc = lpFileOp.wFunc; shfileopstruct.pFrom = lpFileOp.pFrom; shfileopstruct.pTo = lpFileOp.pTo; shfileopstruct.fFlags = lpFileOp.fFlags; shfileopstruct.fAnyOperationsAborted = lpFileOp.fAnyOperationsAborted; shfileopstruct.hNameMappings = lpFileOp.hNameMappings; shfileopstruct.lpszProgressTitle = lpFileOp.lpszProgressTitle; int num2 = SHFileOperation64(ref shfileopstruct); lpFileOp.fAnyOperationsAborted = shfileopstruct.fAnyOperationsAborted; return(num2); }
public void Execute() { WindowInteropHelper wih = new WindowInteropHelper(ParentWindow); SHFILEOPSTRUCT fileOp = new SHFILEOPSTRUCT(); if (this.Flags.HasFlag(FILEOP_FLAGS.FOF_WANTMAPPINGHANDLE)) { throw new NotImplementedException(); } fileOp.hwnd = wih.Handle; fileOp.wFunc = Convert.ToInt32(this.Operation); fileOp.pFrom = ArrayToMultiString(this.From); fileOp.pTo = ArrayToMultiString(this.To); fileOp.fAnyOperationAborted = 0; fileOp.fFlags = Convert.ToInt16(this.Flags); fileOp.hNameMapping = IntPtr.Zero; fileOp.lpszProgressTitle = this.ProgressTitle; int res = SHFileOperation(ref fileOp); }
private const uint ERROR_INVALID_LEVEL = 124; //folder not exist public static void MoveFileToRecycleBin(string path) { const uint delete = 3; const ushort silentNoConfirmationUndo = 84; var fileOp = new SHFILEOPSTRUCT { FileFunc = delete, NamesFrom = path + "\0", //The NamesFrom and NameTo strings must end with two '\ 0'. One will add p/invoke. The result will be two. Flags = silentNoConfirmationUndo }; int hResult = SHFileOperation(ref fileOp); if (hResult != 0) { if (hResult != ERROR_FILE_NOT_FOUND && hResult != ERROR_INVALID_LEVEL) { throw new Win32Exception(hResult); } } }
/// <summary> /// 移动文件(如果文件比较多的话,会出现Window Shell的文件拷贝进度条) /// </summary> /// <param name="srcList"></param> /// <param name="dstList"></param> /// <returns></returns> public static bool SHMoveFiles(string[] srcList, string[] dstList) { string src, dst; if (!ListToSHStr(srcList, dstList, out src, out dst)) { return(false); } Logger.D(string.Format("moveFile: {0} => {1}", src, dst)); SHFILEOPSTRUCT fileop = new SHFILEOPSTRUCT(); fileop.hwnd = IntPtr.Zero; fileop.hNameMappings = IntPtr.Zero; fileop.wFunc = FileFuncFlags.FO_MOVE; fileop.pFrom = src + '\0' + '\0'; fileop.pTo = dst + '\0' + '\0'; fileop.lpszProgressTitle = "文件移动" + '\0' + '\0'; fileop.fFlags = FILEOP_FLAGS.FOF_SIMPLEPROGRESS | FILEOP_FLAGS.FOF_MULTIDESTFILES; return(SHFileOperation(ref fileop) == 0); }
private static bool CopyFilesInternal(List <string> fromList, List <string> toList, FILE_OP_TYPE opType) { bool success = false; string from = FilenamesToShellString(fromList); string to = FilenamesToShellString(toList); SHFILEOPSTRUCT lpFileOp = new SHFILEOPSTRUCT() { wFunc = opType, pFrom = from, pTo = to, fFlags = FILE_OP_FLAGS.FOF_NOCONFIRMMKDIR | FILE_OP_FLAGS.FOF_MULTIDESTFILES }; if (SHFileOperation(ref lpFileOp) == 0) { success = !lpFileOp.fAnyOperationsAborted; } return(success); }
public static bool RenameFiles(List <string> fromList, List <string> toList) { bool success = false; string from = FilenamesToShellString(fromList); string to = FilenamesToShellString(toList); SHFILEOPSTRUCT lpFileOp = new SHFILEOPSTRUCT() { wFunc = FILE_OP_TYPE.FO_RENAME, pFrom = from, pTo = to, fFlags = 0 }; if (SHFileOperation(ref lpFileOp) == 0) { success = !lpFileOp.fAnyOperationsAborted; } return(success); }
public static bool RenameDirectory(string p_strSource, string p_strDest) { SHFILEOPSTRUCT struc = new SHFILEOPSTRUCT(); struc.hNameMappings = IntPtr.Zero; struc.hwnd = IntPtr.Zero; struc.lpszProgressTitle = "Rename Release directory"; struc.pFrom = Marshal.StringToHGlobalUni(p_strSource); struc.pTo = Marshal.StringToHGlobalUni(p_strDest); struc.wFunc = (uint)Operation.FO_RENAME; int ret = SHFileOperation(ref struc); if (ret != 0) { return(false); } else { return(true); } }
public static bool WindowsRecycleFile(string path) { try { SHFILEOPSTRUCT fileop = new SHFILEOPSTRUCT(); fileop.wFunc = FO_DELETE; fileop.pFrom = path + '\0' + '\0'; fileop.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION; int r = SHFileOperation(ref fileop); if (File.Exists(path)) Log.Error("Unable to recycle file" + path); else Log.Info("Recycled file " + path); } catch (Exception ex) { Log.Error("Unable to recycle file " + path, ex); return false; } return true; }
private static bool Send(string path, FileOperationFlags flags) { try { SHFILEOPSTRUCT fileOp = new SHFILEOPSTRUCT { wFunc = FileOperationType.FO_DELETE, pFrom = path + '\0' + '\0', fFlags = (FileOperationFlags)((ushort)(FileOperationFlags.FOF_ALLOWUNDO | flags)) }; SHFileOperation(ref fileOp); return true; } catch (Exception) { return false; } }
/// <summary> /// Actually do the move of a file/directory to the recycleBin /// </summary> /// <param name="path"></param> /// <returns>true if it succeed.</returns> public static bool Recycle(string path) { try { #if MONO // TODO: Find a way in Mono to send something to the recycle bin. try { File.Delete(path); } catch { try { Directory.Delete(path); } catch { } } return true; #else //alternative using visual basic dll: FileSystem.DeleteDirectory(item.FolderPath,UIOption.OnlyErrorDialogs), RecycleOption.SendToRecycleBin); //moves it to the recyle bin var shf = new SHFILEOPSTRUCT(); shf.wFunc = FO_DELETE; shf.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION; string pathWith2Nulls = path + "\0\0"; shf.pFrom = pathWith2Nulls; SHFileOperation(ref shf); return !shf.fAnyOperationsAborted; #endif } catch (Exception exception) { Palaso.Reporting.ErrorReport.NotifyUserOfProblem(exception, "Could not delete that book."); return false; } }
public InteropSHFileOperation() { this.fFlags = new FILEOP_FLAGS(); this._ShFile = new SHFILEOPSTRUCT(); this._ShFile.hwnd = IntPtr.Zero; this._ShFile.wFunc = FO_Func.FO_COPY; this._ShFile.pFrom = ""; this._ShFile.pTo = ""; this._ShFile.fAnyOperationsAborted = 0; this._ShFile.hNameMappings = IntPtr.Zero; this._ShFile.lpszProgressTitle = ""; }
public String lpszProgressTitle; // Address of a string to use as the title of a progress dialog box. #region Constructors // This member is used only if fFlags includes the // FOF_SIMPLEPROGRESS flag. public SHFILEOPSTRUCT64(SHFILEOPSTRUCT initializer) { this.hwnd = initializer.hwnd; this.wFunc = initializer.wFunc; this.pFrom = initializer.pFrom; this.pTo = initializer.pTo; this.fFlags = initializer.fFlags; this.fAnyOperationsAborted = initializer.fAnyOperationsAborted; this.hNameMappings = initializer.hNameMappings; this.lpszProgressTitle = initializer.lpszProgressTitle; }
/// <summary> /// Move specified files to Recycle. /// </summary> /// <param name="filePaths">File paths</param> public static void MoveToRecycle(string[] filePaths) { if ((filePaths == null) || !filePaths.Any()) return; var filePathCombined = String.Join("\0", filePaths) + '\0' + '\0'; var sh = new SHFILEOPSTRUCT { hwnd = IntPtr.Zero, wFunc = FO.FO_DELETE, pFrom = filePathCombined, pTo = null, // FOF_SILENT is necessary to prevent this application's window from losing focus. fFlags = FOF.FOF_ALLOWUNDO | FOF.FOF_NOCONFIRMATION | FOF.FOF_SILENT, fAnyOperationsAborted = false, hNameMappings = IntPtr.Zero, lpszProgressTitle = null, }; var result = SHFileOperation(ref sh); if (result != 0) // 0 means success or user canceled operation (it will never happen in this application). throw new Win32Exception(String.Format("Failed to move files to Recycle. Error code: {0} File paths: {1}", result, String.Join(",", filePaths))); }
public static extern Int32 SHFileOperation( ref SHFILEOPSTRUCT lpFileOp);
public bool Trash() { SHFILEOPSTRUCT fileOp = new SHFILEOPSTRUCT(); fileOp.wFunc = FO_DELETE; fileOp.pFrom = ImagePath + '\0' + '\0'; fileOp.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_NOERRORUI; int ret = SHFileOperation(ref fileOp); return (ret == 0 && !fileOp.fAnyOperationsAborted); }
private static bool CopyFiles(string from, string to) { bool success = false; SHFILEOPSTRUCT lpFileOp = new SHFILEOPSTRUCT(); lpFileOp.hwnd = IntPtr.Zero; lpFileOp.wFunc = FILE_OP_TYPE.FO_COPY; lpFileOp.pFrom = from; lpFileOp.pTo = to; lpFileOp.fFlags = FILE_OP_FLAGS.FOF_NORECURSION | FILE_OP_FLAGS.FOF_NOCONFIRMMKDIR | FILE_OP_FLAGS.FOF_MULTIDESTFILES; lpFileOp.fAnyOperationsAborted = false; lpFileOp.hNameMappings = IntPtr.Zero; lpFileOp.lpszProgressTitle = string.Empty; //do copy operation and store result int result = SHFileOperation(ref lpFileOp); //we also need to check for user aborted operations if (result == 0) { success = !lpFileOp.fAnyOperationsAborted; } return success; }
public static bool RecycleFile(Form parentForm, String filename) { SHFILEOPSTRUCT shf = new SHFILEOPSTRUCT(); shf.hwnd = parentForm.Handle; shf.wFunc = FO_DELETE; shf.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION; shf.pFrom = filename + "\0\0"; int res = SHFileOperation(ref shf); return (res == 0); }
// this function needs to carry out the specified operation. This // parameter must contain a valid value that is not NULL. You are // responsibile for validating the value. If you do not validate it, // you will experience unexpected results. public static Int32 SHFileOperation(ref SHFILEOPSTRUCT lpFileOp) { MachineType mt = GetMachineType(); Int32 result; switch (mt) { case MachineType.win32: SHFILEOPSTRUCT32 fos32 = new SHFILEOPSTRUCT32(lpFileOp); result = SHFileOperation32(ref fos32); lpFileOp.CopyFrom(fos32); break; case MachineType.win64: SHFILEOPSTRUCT64 fos64 = new SHFILEOPSTRUCT64(lpFileOp); result = SHFileOperation64(ref fos64); lpFileOp.CopyFrom(fos64); break; default: throw new ArgumentException("Hell, what kind of computer are you using? It's not 32 and not 64 bit"); } return result; }
public static void SendFileToRecycleBin(string filePath) { SHFILEOPSTRUCT shf = new SHFILEOPSTRUCT(); shf.wFunc = FO_DELETE; shf.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION; shf.pFrom = filePath; SHFileOperation(ref shf); }
static extern int SHFileOperation(ref SHFILEOPSTRUCT FileOp);
private static extern int SHFileOperation(ref SHFILEOPSTRUCT lpFileOp);