這個範例,分享2個重點,一是 c# 如何 copy file, 二是 try catch 的使用,取得實際錯誤的訊息:
using System; using System.IO; class Program { static void Main() { // Copying a file that doesn't exist: try { File.Copy("file-missing.txt", "file-new.txt"); } catch (Exception ex) { Console.WriteLine(ex); // System.IO.FileNotFoundException: Could not find file 'file-missing.txt'. } // Copying to a file without overwrite try { File.Copy("file-a.txt", "file-b.txt"); } catch (Exception ex) { Console.WriteLine(ex); // System.IO.IOException: The file 'file-b.txt' already exists. } } }