Link to home
Start Free TrialLog in
Avatar of xiaoxin85
xiaoxin85

asked on

Copy file method do not create folder???

String ^source = "C:/a.txt";
String ^destination = "C:/folder/a.txt";
try
   {
      // Ensure that the target does not exist.
      File::Delete( destination );
     
      // Copy the file.
      File::Copy( source, destination );
      Console::WriteLine( "{0} copied to {1}", source, destination );
     
      // Try to copy the same file again, which should fail.
      File::Copy( source, destination );
      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 );
   }

The above code when I tried do not work becoz I had it to copy to a destination folder where it does not exist, how to create I automatic create the copy for it to copy to????
ASKER CERTIFIED SOLUTION
Avatar of gregoryyoung
gregoryyoung
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
And moreover the second copy will also be succeeded bcoz you are not moving the file, just copying the file... Before deleting a file check whether the file exists else it will throw an exception


               File::Exists


To make the directory creation common, since destination path may change use the following

               String ^destination = "C:/folder/a.txt";

               FileInfo^ finfo = gcnew FileInfo("C:/folder/a.txt");

                if (!Directory::Exists(finfo->Directory))
                    Directory::CreateDirectory(finfo->Directory);


Sorry if any mistake in my code... I am a C# developer :(