File Operations
Use case
You need to read and write files: configs, logs, data dumps, or any text/binary file. Rust’s standard library covers the basics without external crates.
In C#: Like File.ReadAllText, File.WriteAllText, File.ReadAllLines, Path.Combine, and StreamReader/StreamWriter.
Paths: std::path
Use Path and PathBuf for cross-platform paths. Path is like a slice (borrowed); PathBuf is owned (mutable).
use std::path::Path;
let path = Path::new("/tmp/hello.txt");
let parent = path.parent(); // Some(Path("/tmp"))
let name = path.file_name(); // Some(OsStr("hello.txt"))In C#: Like Path.GetDirectoryName, Path.GetFileName. In Rust, PathBuf::from("dir").join("file.txt") is like Path.Combine("dir", "file.txt").
Reading a file
std::fs::read_to_string reads the whole file into a String. Returns Result<String, std::io::Error>.
use std::fs;
let content = fs::read_to_string("config.toml")?; // in a function that returns Result
// or
match fs::read_to_string("config.toml") {
Ok(s) => println!("{}", s),
Err(e) => eprintln!("error: {}", e),
}In C#: Like File.ReadAllText("config.toml") (Rust uses Result instead of exceptions). For binary: fs::read("file.bin") returns Vec<u8> (like File.ReadAllBytes).
Writing a file
std::fs::write overwrites the file with the given bytes. For text, pass a &str or String.
use std::fs;
fs::write("output.txt", "Hello, file!")?;
fs::write("output.txt", data.as_bytes())?; // bytesIn C#: Like File.WriteAllText("output.txt", "Hello, file!"). To append, open the file with OpenOptions (see below).
Append and OpenOptions
To append instead of overwrite, use std::fs::OpenOptions and a BufWriter or write! macro:
use std::fs::OpenOptions;
use std::io::Write;
let mut f = OpenOptions::new().append(true).open("log.txt")?;
writeln!(f, "new line")?;In C#: Like opening a FileStream with FileMode.Append and using a StreamWriter.
Creating directories
use std::fs;
fs::create_dir("mydir")?; // fails if parent missing
fs::create_dir_all("a/b/c")?; // creates all parentsIn C#: Like Directory.CreateDirectory("a/b/c") (create all is default in .NET).
Key takeaway
Use fs::read_to_string / fs::read to read, fs::write to write. Use Path/PathBuf for paths and OpenOptions for append or other modes. All I/O returns Result; use ? or match to handle errors.