Exemplo n.º 1
0
        public static bool DeleteToRecycleBin(string filePath, FileOperationFlags flags)
        {
            if (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
                try
                {
                    var shf = new SHFILEOPSTRUCT
                    {
                        wFunc  = FileOperationType.FO_DELETE,
                        pFrom  = filePath + '\0' + '\0',
                        fFlags = FileOperationFlags.FOF_ALLOWUNDO | flags
                    };

                    SHFileOperation(ref shf);
                    return(!shf.fAnyOperationsAborted);
                }
                catch (Exception)
                {
                    return(false);
                }
            }

            // 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);
        }