using System;
using System.Collections.Generic;
using System.Text;
using System.IO;namespace copy_file1
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = @"c:\temp\MyTest.txt";
            string path2 = path + "temp";            try
            {
                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 fail.
                File.Copy(path, path2);
                Console.WriteLine("The second Copy operation succeeded, which was not expected.");
            }            catch (Exception e)
            {
                Console.WriteLine("Double copying is not allowed, as expected.");
                Console.WriteLine(e.ToString());
            }        }
    }
}

解决方案 »

  1.   

    这可是 MSDN 里的例子啊。想不明白。等高手。
      

  2.   


    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.IO;namespace copy_file1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string path = @"c:\temp\MyTest.txt";
                string path2 = path + "temp";            try
                {
                    //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 fail. 
                    File.Copy(path, path2);
                    Console.WriteLine("The second Copy operation succeeded, which was not expected.");
                }            catch (Exception e)
                {
                    Console.WriteLine("Double copying is not allowed, as expected.");
                    Console.WriteLine(e.ToString());
                }        }
        }
    }
      

  3.   


    using (FileStream fs = File.Create(path)) { } 
    // Ensure that the target does not exist. 
    File.Delete(path2); 这里用Create的形式OpenStream,path为源文件,就变为空文件了。
      

  4.   

    //using (FileStream fs = File.Create(path)) { }
     3楼的办法可以,我也是这样试出来的。但是不知道为什么要注释掉这一行。  
     是重新创建了那个path的文件,是吗?