FAQ - Help and questions

How do I show an open or save file dialog from a Rust desktop app?

#file-dialog#rfd#desktop#guipublished 2 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail
Last post

Short answer

The rfd crate shows the system's open, save and folder dialogs on Windows, macOS and Linux, with filters and a start name. FileDialog blocks until the user answers and returns None when they cancel. AsyncFileDialog gives the same dialogs as a future. The code passed cargo check on Windows.

Checked with rustc 1.93.0, Windows 11, rfd 0.18.0; `cargo check` only. No dialog was opened for this thread, and macOS behaviour was not tested.

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

rfd ("Rusty File Dialogs") shows the file dialogs of the operating system and works with any toolkit, because it does not need your window. Its README lists Windows, macOS and Linux and BSD (through GTK or the XDG desktop portal) as supported, and says it provides both asynchronous and synchronous APIs. Answer 1 below is the synchronous one and answer 2 the asynchronous one.

Cargo.tomltoml
[dependencies]
rfd = "0.18"
    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    2 answers from the Ruststudio team: different approaches, each with its own trade-offs

    Sort: Oldest Newest
    #2

    Approach 1: the blocking FileDialog#

    Use it for a quick tool, or from a worker thread. The call returns when the user picks something or cancels.

    src/main.rsrust
    use rfd::FileDialog;
    use std::path::PathBuf;
    
    fn open_text_file() -> Option<PathBuf> {
        FileDialog::new()
            .set_title("Open a text file")
            .add_filter("Text", &["txt", "md"])
            .add_filter("All files", &["*"])
            .pick_file() // blocks until the user answers; None means "cancelled"
    }
    
    fn save_as(suggested: &str) -> Option<PathBuf> {
        FileDialog::new().set_file_name(suggested).add_filter("Text", &["txt"]).save_file()
    }

    None is a normal answer, not an error: the user pressed Cancel. Handle it by doing nothing.

    Trade-off: while the dialog is open the calling thread waits. If that thread is the UI thread, the toolkit's own window is not served meanwhile; whether that is acceptable depends on the toolkit. Read the rfd documentation for the platform notes before calling it from inside an event handler.

      QuoteReply
      Share
      Hacker NewsRedditLinkedInE-mail
      #3

      Approach 2: the AsyncFileDialog#

      Use it when your program already has an async runtime or an executor, or when the toolkit offers a way to run a future and get a message back.

      src/main.rsrust
      async fn open_async() -> Option<Vec<u8>> {
          // The async version does not block the thread that calls it.
          let handle = rfd::AsyncFileDialog::new().pick_file().await?;
          Some(handle.read().await)
      }

      The read() call on the returned handle reads the file's bytes; handle.path() gives the path where there is one. Both snippets passed cargo check together in one file with rfd 0.18.0 on Windows 11. They were not run, so no dialog was ever shown.

      Trade-off: needs something to drive the future, and the result arrives later, so the UI should be ready for "no answer yet".

      Common mistakes#

      • Treating a cancelled dialog as an error.
      • Forgetting the file type filter. Without one, the user can pick anything and your parser has to cope.
      • Reading the file in the UI thread after the dialog. Large files should be read on a worker (see the thread on background work).

      Can I set the starting folder?#

      Yes: FileDialog has a set_directory method. Pass the folder the user used last time, which your settings file can remember.

      Sources#

        QuoteReply
        Share
        Hacker NewsRedditLinkedInE-mail