首页 最新 热门 推荐

  • 首页
  • 最新
  • 热门
  • 推荐

20250226 工作隨筆 C#文件拷貝

  • 25-03-04 19:02
  • 2323
  • 8301
blog.csdn.net
  1. public bool CopyFileToDestination(DbConnect db, string sourceFilePath, Enums.OutputKubun outputKubun, int detailId = 3)
  2. {
  3. // 1.元のパスが存在しない場合はロールバックして終了
  4. if (string.IsNullOrWhiteSpace(sourceFilePath) || !File.Exists(sourceFilePath))
  5. {
  6. db.Rollback();
  7. return false;
  8. }
  9. // 2.対象となる出力フォルダー情報をデータベースから取得
  10. DataTable fileTable = ExportFileModel.SQL.Get(db, (int)outputKubun, detailId);
  11. string? destinationDirectory = fileTable.Rows.Count > 0 ? Convert.ToString(fileTable.Rows[0]["output_path"]) : string.Empty;
  12. // 3.ターゲットフォルダのパスが空/空白の場合ロールバックして終了
  13. if (string.IsNullOrWhiteSpace(destinationDirectory))
  14. {
  15. db.Rollback();
  16. return false;
  17. }
  18. // 4.ターゲットフォルダの物理存在を検証(存在しない場合ロールバックして終了)
  19. if (!Directory.Exists(destinationDirectory))
  20. {
  21. db.Rollback();
  22. return false;
  23. }
  24. // 5.完全な目的地ファイルパスを生成
  25. string destinationPath = Path.Combine(destinationDirectory, Path.GetFileName(sourceFilePath));
  26. // 6.ファイルを目的地にコピー(既存の場合は上書き)
  27. File.Copy(sourceFilePath, destinationPath, true);
  28. return true;
  29. }

 

? 代碼解析:CopyFileToDestination 方法

這個方法的功能是將 CSV 文件從 sourceFilePath 拷貝到數據庫指定的 output_path 目錄下,並根據不同條件進行校驗與回滾。方法的返回值是 bool,表示操作是否成功。


? 方法簽名

  1. public bool CopyFileToDestination(DbConnect db, string sourceFilePath, Enums.OutputKubun outputKubun, int detailId = 3)
  • db:數據庫連接對象, 用於查詢目標文件夾路徑,並在異常情況下進行回滾。
  • sourceFilePath:要複製的源 CSV 文件的完整路徑。
  • outputKubun:輸出類別的枚舉,用於查詢數據庫的 output_path。
  • detailId:默認值為 3,用於查詢時的參數。

? 代碼詳解(含中文註釋)

  1. // 1. 如果源文件路徑為空或該文件不存在,則回滾事務並返回 false
  2. if (string.IsNullOrWhiteSpace(sourceFilePath) || !File.Exists(sourceFilePath))
  3. {
  4. db.Rollback();
  5. return false;
  6. }

✅ 目的:

  • 確保 sourceFilePath 非空(防止空參數)。
  • 確保文件存在(避免無效路徑拷貝)。
  • 如果條件不滿足,則回滾數據庫並返回 false。

  1. // 2. 從數據庫查詢對應的輸出文件夾路徑
  2. DataTable fileTable = ExportFileModel.SQL.Get(db, (int)outputKubun, detailId);
  3. string? destinationDirectory = fileTable.Rows.Count > 0 ? Convert.ToString(fileTable.Rows[0]["output_path"]) : string.Empty;

✅ 目的:

  • 從數據庫查詢 output_path,即目標文件夾的路徑。
  • 若 fileTable 中有數據,則從第一行獲取 output_path,否則返回 string.Empty(空字符串)。

  1. // 3. 如果目標文件夾路徑為空或全是空格,則回滾事務並返回 false
  2. if (string.IsNullOrWhiteSpace(destinationDirectory))
  3. {
  4. db.Rollback();
  5. return false;
  6. }

✅ 目的:

  • 確保 output_path 有效(不能是空字符串、空白字符或 null)。
  • 若無效,則回滾數據庫並返回 false。

  1. // 4. 確保目標文件夾物理存在,如果不存在則回滾並返回 false
  2. if (!Directory.Exists(destinationDirectory))
  3. {
  4. db.Rollback();
  5. return false;
  6. }

✅ 目的:

  • 確保數據庫返回的 output_path 對應的文件夾真實存在。
  • ❌ 缺點:這裡的處理方式是若目錄不存在則直接返回 false,但更好的做法是創建該目錄(見後續優化)。

  1. // 5. 生成完整的目標文件路徑,確保文件名稱不變
  2. string destinationPath = Path.Combine(destinationDirectory, Path.GetFileName(sourceFilePath));

✅ 目的:

  • 獲取原始文件名:使用 Path.GetFileName(sourceFilePath) 確保不會改變文件名。
  • 拼接目標路徑:Path.Combine(destinationDirectory, 原文件名) 得到完整的目標文件路徑。

  1. // 6. 執行文件拷貝(如果目標文件已存在,則覆蓋)
  2. File.Copy(sourceFilePath, destinationPath, true);

✅ 目的:

  • 將源 CSV 文件拷貝到 destinationDirectory 目錄下。
  • true 參數表示 如果目標文件已經存在,則覆蓋。

return true;

✅ 目的:

  • 文件成功拷貝後返回 true,表示操作成功。

? 存在的問題

  1. 目標文件夾不存在時,應自動創建,而不是直接回滾
    • Directory.Exists(destinationDirectory) 檢查文件夾時,當文件夾不存在應該 CreateDirectory(destinationDirectory),而不是直接 return false。
  2. 異常處理不足
    • File.Copy() 可能會拋異常(例如無權限),應該用 try-catch 捕獲異常並記錄錯誤日誌。

✅ 優化後的版本

  1. public bool CopyFileToDestination(DbConnect db, string sourceFilePath, Enums.OutputKubun outputKubun, int detailId = 3)
  2. {
  3. // 1. 檢查源文件是否有效
  4. if (string.IsNullOrWhiteSpace(sourceFilePath) || !File.Exists(sourceFilePath))
  5. {
  6. Console.WriteLine("源文件不存在或路徑無效:" + sourceFilePath);
  7. db.Rollback();
  8. return false;
  9. }
  10. // 2. 從數據庫獲取目標文件夾路徑
  11. DataTable fileTable = ExportFileModel.SQL.Get(db, (int)outputKubun, detailId);
  12. string? destinationDirectory = fileTable.Rows.Count > 0 ? Convert.ToString(fileTable.Rows[0]["output_path"]) : string.Empty;
  13. // 3. 確保目標文件夾有效
  14. if (string.IsNullOrWhiteSpace(destinationDirectory))
  15. {
  16. Console.WriteLine("數據庫返回的目標文件夾路徑無效");
  17. db.Rollback();
  18. return false;
  19. }
  20. try
  21. {
  22. // 4. 確保目標文件夾存在,如果不存在則創建
  23. Directory.CreateDirectory(destinationDirectory);
  24. // 5. 獲取目標文件的完整路徑
  25. string destinationPath = Path.Combine(destinationDirectory, Path.GetFileName(sourceFilePath));
  26. // 6. 執行文件拷貝(如果已存在則覆蓋)
  27. File.Copy(sourceFilePath, destinationPath, true);
  28. }
  29. catch (Exception ex)
  30. {
  31. Console.WriteLine("文件拷貝失敗:" + ex.Message);
  32. db.Rollback();
  33. return false;
  34. }
  35. return true;
  36. }

? 優化點

  1. 自動創建目標文件夾

    • Directory.CreateDirectory(destinationDirectory) 如果文件夾已存在,不會拋異常,不存在時則會自動創建,避免了 if (!Directory.Exists(...)) 的判斷。
  2. 增加 Console.WriteLine,方便調試

    • 提供更詳細的錯誤信息,例如 源文件不存在、數據庫目錄無效、文件拷貝失敗等。
  3. 使用 try-catch 捕獲異常

    • 避免 File.Copy() 失敗時直接崩潰(如無權限、目標文件夾被占用等)。
    • 發生異常時,記錄錯誤並回滾數據庫。

? 總結

版本問題點優化點
原始版本目標文件夾不存在時直接 return false自動創建目標文件夾
沒有異常處理增加 try-catch 來避免程序崩潰
缺少錯誤信息輸出Console.WriteLine() 輸出錯誤原因

這樣,新的 CopyFileToDestination 方法在安全性、健壯性、可讀性方面都有了明顯提升 ?。

? 代碼解析:CopyFileToDestination 方法

這個方法的功能是將 CSV 文件從 sourceFilePath 拷貝到數據庫指定的 output_path 目錄下,並根據不同條件進行校驗與回滾。方法的返回值是 bool,表示操作是否成功。


? 方法簽名

  1. public bool CopyFileToDestination(DbConnect db, string sourceFilePath, Enums.OutputKubun outputKubun, int detailId = 3)
  • db:數據庫連接對象, 用於查詢目標文件夾路徑,並在異常情況下進行回滾。
  • sourceFilePath:要複製的源 CSV 文件的完整路徑。
  • outputKubun:輸出類別的枚舉,用於查詢數據庫的 output_path。
  • detailId:默認值為 3,用於查詢時的參數。

? 代碼詳解(含中文註釋)

  1. // 1. 如果源文件路徑為空或該文件不存在,則回滾事務並返回 false
  2. if (string.IsNullOrWhiteSpace(sourceFilePath) || !File.Exists(sourceFilePath))
  3. {
  4. db.Rollback();
  5. return false;
  6. }

✅ 目的:

  • 確保 sourceFilePath 非空(防止空參數)。
  • 確保文件存在(避免無效路徑拷貝)。
  • 如果條件不滿足,則回滾數據庫並返回 false。

  1. // 2. 從數據庫查詢對應的輸出文件夾路徑
  2. DataTable fileTable = ExportFileModel.SQL.Get(db, (int)outputKubun, detailId);
  3. string? destinationDirectory = fileTable.Rows.Count > 0 ? Convert.ToString(fileTable.Rows[0]["output_path"]) : string.Empty;

✅ 目的:

  • 從數據庫查詢 output_path,即目標文件夾的路徑。
  • 若 fileTable 中有數據,則從第一行獲取 output_path,否則返回 string.Empty(空字符串)。

  1. // 3. 如果目標文件夾路徑為空或全是空格,則回滾事務並返回 false
  2. if (string.IsNullOrWhiteSpace(destinationDirectory))
  3. {
  4. db.Rollback();
  5. return false;
  6. }

✅ 目的:

  • 確保 output_path 有效(不能是空字符串、空白字符或 null)。
  • 若無效,則回滾數據庫並返回 false。

  1. // 4. 確保目標文件夾物理存在,如果不存在則回滾並返回 false
  2. if (!Directory.Exists(destinationDirectory))
  3. {
  4. db.Rollback();
  5. return false;
  6. }

✅ 目的:

  • 確保數據庫返回的 output_path 對應的文件夾真實存在。
  • ❌ 缺點:這裡的處理方式是若目錄不存在則直接返回 false,但更好的做法是創建該目錄(見後續優化)。

  1. // 5. 生成完整的目標文件路徑,確保文件名稱不變
  2. string destinationPath = Path.Combine(destinationDirectory, Path.GetFileName(sourceFilePath));

✅ 目的:

  • 獲取原始文件名:使用 Path.GetFileName(sourceFilePath) 確保不會改變文件名。
  • 拼接目標路徑:Path.Combine(destinationDirectory, 原文件名) 得到完整的目標文件路徑。

  1. // 6. 執行文件拷貝(如果目標文件已存在,則覆蓋)
  2. File.Copy(sourceFilePath, destinationPath, true);

✅ 目的:

  • 將源 CSV 文件拷貝到 destinationDirectory 目錄下。
  • true 參數表示 如果目標文件已經存在,則覆蓋。

return true;

✅ 目的:

  • 文件成功拷貝後返回 true,表示操作成功。

? 存在的問題

  1. 目標文件夾不存在時,應自動創建,而不是直接回滾
    • Directory.Exists(destinationDirectory) 檢查文件夾時,當文件夾不存在應該 CreateDirectory(destinationDirectory),而不是直接 return false。
  2. 異常處理不足
    • File.Copy() 可能會拋異常(例如無權限),應該用 try-catch 捕獲異常並記錄錯誤日誌。

✅ 優化後的版本

  1. public bool CopyFileToDestination(DbConnect db, string sourceFilePath, Enums.OutputKubun outputKubun, int detailId = 3)
  2. {
  3. // 1. 檢查源文件是否有效
  4. if (string.IsNullOrWhiteSpace(sourceFilePath) || !File.Exists(sourceFilePath))
  5. {
  6. Console.WriteLine("源文件不存在或路徑無效:" + sourceFilePath);
  7. db.Rollback();
  8. return false;
  9. }
  10. // 2. 從數據庫獲取目標文件夾路徑
  11. DataTable fileTable = ExportFileModel.SQL.Get(db, (int)outputKubun, detailId);
  12. string? destinationDirectory = fileTable.Rows.Count > 0 ? Convert.ToString(fileTable.Rows[0]["output_path"]) : string.Empty;
  13. // 3. 確保目標文件夾有效
  14. if (string.IsNullOrWhiteSpace(destinationDirectory))
  15. {
  16. Console.WriteLine("數據庫返回的目標文件夾路徑無效");
  17. db.Rollback();
  18. return false;
  19. }
  20. try
  21. {
  22. // 4. 確保目標文件夾存在,如果不存在則創建
  23. Directory.CreateDirectory(destinationDirectory);
  24. // 5. 獲取目標文件的完整路徑
  25. string destinationPath = Path.Combine(destinationDirectory, Path.GetFileName(sourceFilePath));
  26. // 6. 執行文件拷貝(如果已存在則覆蓋)
  27. File.Copy(sourceFilePath, destinationPath, true);
  28. }
  29. catch (Exception ex)
  30. {
  31. Console.WriteLine("文件拷貝失敗:" + ex.Message);
  32. db.Rollback();
  33. return false;
  34. }
  35. return true;
  36. }

? 優化點

  1. 自動創建目標文件夾

    • Directory.CreateDirectory(destinationDirectory) 如果文件夾已存在,不會拋異常,不存在時則會自動創建,避免了 if (!Directory.Exists(...)) 的判斷。
  2. 增加 Console.WriteLine,方便調試

    • 提供更詳細的錯誤信息,例如 源文件不存在、數據庫目錄無效、文件拷貝失敗等。
  3. 使用 try-catch 捕獲異常

    • 避免 File.Copy() 失敗時直接崩潰(如無權限、目標文件夾被占用等)。
    • 發生異常時,記錄錯誤並回滾數據庫。

? 總結

版本問題點優化點
原始版本目標文件夾不存在時直接 return false自動創建目標文件夾
沒有異常處理增加 try-catch 來避免程序崩潰
缺少錯誤信息輸出Console.WriteLine() 輸出錯誤原因

這樣,新的 CopyFileToDestination 方法在安全性、健壯性、可讀性方面都有了明顯提升 ?。

注:本文转载自blog.csdn.net的靈臺清明的文章"https://blog.csdn.net/2301_79992621/article/details/145881003"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接
复制链接
相关推荐
发表评论
登录后才能发表评论和回复 注册

/ 登录

评论记录:

未查询到任何数据!
回复评论:

分类栏目

后端 (14832) 前端 (14280) 移动开发 (3760) 编程语言 (3851) Java (3904) Python (3298) 人工智能 (10119) AIGC (2810) 大数据 (3499) 数据库 (3945) 数据结构与算法 (3757) 音视频 (2669) 云原生 (3145) 云平台 (2965) 前沿技术 (2993) 开源 (2160) 小程序 (2860) 运维 (2533) 服务器 (2698) 操作系统 (2325) 硬件开发 (2491) 嵌入式 (2955) 微软技术 (2769) 软件工程 (2056) 测试 (2865) 网络空间安全 (2948) 网络与通信 (2797) 用户体验设计 (2592) 学习和成长 (2593) 搜索 (2744) 开发工具 (7108) 游戏 (2829) HarmonyOS (2935) 区块链 (2782) 数学 (3112) 3C硬件 (2759) 资讯 (2909) Android (4709) iOS (1850) 代码人生 (3043) 阅读 (2841)

热门文章

101
推荐
关于我们 隐私政策 免责声明 联系我们
Copyright © 2020-2025 蚁人论坛 (iYenn.com) All Rights Reserved.
Scroll to Top