file_reader.rs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. use std::fs;
  2. use std::path::Path;
  3. #[tauri::command]
  4. pub fn read_file_content(path: String) -> Result<String, String> {
  5. fs::read_to_string(&path)
  6. .map_err(|e| format!("无法读取文件 {}: {}", path, e))
  7. }
  8. #[tauri::command]
  9. pub fn list_directory_files(path: String) -> Result<Vec<String>, String> {
  10. let dir = Path::new(&path);
  11. if !dir.exists() {
  12. return Ok(Vec::new());
  13. }
  14. if !dir.is_dir() {
  15. return Err(format!("{} 不是一个目录", path));
  16. }
  17. let mut files = Vec::new();
  18. match fs::read_dir(dir) {
  19. Ok(entries) => {
  20. for entry in entries {
  21. if let Ok(entry) = entry {
  22. if let Ok(file_type) = entry.file_type() {
  23. if file_type.is_file() {
  24. if let Some(file_name) = entry.file_name().to_str() {
  25. files.push(file_name.to_string());
  26. }
  27. }
  28. }
  29. }
  30. }
  31. Ok(files)
  32. }
  33. Err(e) => Err(format!("无法读取目录 {}: {}", path, e))
  34. }
  35. }