Recover file from Trash

Hi,
There is a g_file_trash() to put the file into the Trash, but there is no g_file_undelete() to recover it.

What is the way to do so?

Thank you.

Hi,

It is cancellable. (gio/gfile.c)


/**
4008  * g_file_trash:
4009  * @file: #GFile to send to trash
4010  * @cancellable: (nullable): optional #GCancellable object,
4011  *     %NULL to ignore
4012  * @error: a #GError, or %NULL
4013  *
4014  * Sends @file to the "Trashcan", if possible. This is similar to
4015  * deleting it, but the user can recover it before emptying the trashcan.
4016  * Not all file systems support trashing, so this call can return the
4017  * %G_IO_ERROR_NOT_SUPPORTED error.
4018  *
4019  * If @cancellable is not %NULL, then the operation can be cancelled by
4020  * triggering the cancellable object from another thread. If the operation
4021  * was cancelled, the error %G_IO_ERROR_CANCELLED will be returned.
4022  *
4023  * Virtual: trash
4024  * Returns: %TRUE on successful trash, %FALSE otherwise.
4025  */

But I can’t write a example, sorry!
Gnome Nautilus can move files to trash and remove them from there, so looking at the source could be interesting.

There is no “recover from trash” operation, as various file systems do not support a trash bin, or do not support enumerating the trash bin contents, or can have different trash bins depending on the volume. It’s generally better to leave it to the user to deal with file recovery.

Moving a file to the trash bin involved moving the file and creating additional metadata for its recovery; recovering from the trash on Linux systems is kind of complicated and it might involve things like asking the user, so it can’t really be done in GIO.

If you want to implement an “undo” operation, you should probably keep the file contents available for a certain amount of time, and store them back into the file at the original location. You can also open a file descriptor to the file, if it’s local and on Linux, and hold it for a certain amount of time; this will keep the file alive in the kernel, and you’ll still be allowed to read from it.

Nautilus just moves the file back, with a g_file_move. https://gitlab.gnome.org/GNOME/nautilus/blob/master/src/nautilus-file-undo-operations.c#L609

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.