Tauri File System Access: Read, Write & Native Dialogs | Rust + React Tutorial (Lesson 35)
Video: Tauri File System Access: Read, Write & Native Dialogs | Rust + React Tutorial (Lesson 35) by Taught by Celeste AI - AI Coding Coach
Watch full page →Tauri File System Access: Read, Write & Native Dialogs
Discover how to securely interact with the file system in a Tauri desktop app using Rust and React. This guide covers Tauri’s capability-based permissions, reading and writing files with Rust’s standard library, and implementing native open/save dialogs with the tauri-plugin-dialog plugin.
Code
use std::fs;
use tauri::api::path;
use tauri_plugin_dialog::{open, save};
// Command to read a file's contents as a String
#[tauri::command]
fn read_file(path: String) -> Result {
fs::read_to_string(&path).map_err(|e| e.to_string())
}
// Command to write contents to a file, creating or overwriting it
#[tauri::command]
fn write_file(path: String, contents: String) -> Result<(), String> {
fs::write(&path, contents).map_err(|e| e.to_string())
}
// Example React usage (TypeScript):
/*
import { open, save } from 'tauri-plugin-dialog-api';
async function openFile() {
const selected = await open({
multiple: false,
filters: [{ name: 'Text Files', extensions: ['txt', 'md'] }],
});
if (selected) {
// send selected path to backend command read_file
}
}
async function saveFile(defaultName: string) {
const savePath = await save({
defaultPath: defaultName,
filters: [{ name: 'Text Files', extensions: ['txt'] }],
});
if (savePath) {
// send savePath and contents to backend command write_file
}
}
*/
// Access standard app directories
fn get_app_dirs() {
let config_dir = path::config_dir().unwrap(); // e.g. ~/Library/Application Support on macOS
let data_dir = path::data_dir().unwrap(); // e.g. AppData on Windows
let cache_dir = path::cache_dir().unwrap(); // e.g. ~/.cache on Linux
println!("Config: {:?}, Data: {:?}, Cache: {:?}", config_dir, data_dir, cache_dir);
}
Key Points
- Tauri enforces explicit permissions for file system operations using a capability-based security model.
- Use Rust’s std::fs functions like read_to_string and write for safe, idiomatic file reading and writing.
- The tauri-plugin-dialog plugin provides native open and save dialogs that integrate with the OS look and feel.
- Standard app directories (config, data, cache) help your app store files in platform-appropriate locations.
- React frontend communicates with Rust backend commands to perform file operations securely and asynchronously.