C# program that demonstrates File.Copy exceptions

這個範例,分享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.
        }
    }
}

相關文章

寫留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *