How to know that File.Copy succeeded?

前端 未结 5 2129
Happy的楠姐
Happy的楠姐 2020-12-18 19:48

The static method File.Copy(String, String) doesn\'t return a value. How can I know programatically if that function succeeded or not ? If there is no thrown ex

5条回答
  •  悲&欢浪女
    2020-12-18 20:39

    if there is no exception that it means that the file is success fully copied ...

    using System;
    using System.IO;
    
    class Test 
    {
        public static void Main() 
        {
            string path = @"c:\temp\MyTest.txt";
            string path2 = path + "temp";
    
            try 
            {
                // Create the file and clean up handles.
                using (FileStream fs = File.Create(path)) {}
    
                // Ensure that the target does not exist.
                File.Delete(path2);
    
                // Copy the file.
                File.Copy(path, path2);
                Console.WriteLine("{0} copied to {1}", path, path2);
    
                // Try to copy the same file again, which should succeed.
                File.Copy(path, path2, true);
                Console.WriteLine("The second Copy operation succeeded, which was expected.");
            } 
    
            catch 
            {
                Console.WriteLine("Double copy is not allowed, which was not expected.");
            }
        }
    }
    

提交回复
热议问题