Copy A File To Desktop

back to Errata index


using System;
using System.IO;

class Program {

    static void Main() {

        string sPath = string.Empty;

        if (!File.Exists("myfile.txt")) {

            StreamWriter sw;
            sw = File.CreateText("myfile.txt");
            sw.WriteLine("This is my example text file");
            sw.Close();
            
            Console.WriteLine();

        }

        Console.WriteLine("There is a file named \"myfile.txt\" in the application's executable directory.");
        Console.WriteLine("To copy it so that it's also on your desktop, press a key... ");
        Console.ReadLine();

        sPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.DesktopDirectory) + "\\myfile.txt";
        //Console.WriteLine(sPath);


        try {

            File.Copy("myfile.txt", sPath, true);
            File.Delete("myfile.txt");
            Console.WriteLine("\"myfile.txt\" was successfully copied to your desktop");

        } catch(Exception e) {

            Console.WriteLine(e.Message);

        }
  

        Console.WriteLine("\nPress the Enter key to end program... ");
        Console.ReadLine();

    }//end method Main()

}//end class Program