none
File.Copy or File.Move with Overwrite RRS feed

  • Question

  •  

    Hi all,

    I am trying to either copy or move a file after passing or failing validation.

    However the file may already exist .in the destination

    As per here http://msdn2.microsoft.com/en-us/library/9706cfs5.aspx

    I have used the boolean overwrite to True

     

    My code is File.Copy(filename, "c:\\Filechecker\\inboxbackup\\" + basename, true);

    but I get the error

    'System.IO.IOException' Cannot create a file when that file already exists

     

    Am I usung the overwrite correctly ?

    What about checking if the file exists first and deleting ?

    Would that work

     

    Ray..

    Monday, April 21, 2008 10:23 PM

Answers

  • Thx for both your help..

    It helped me come up with the following

     


    // check if file already exists in inboxbackup if it does then delete
    if (File.Exists("c:\\Filechecker\\inboxbackup\\" + basename) )
    {
    File.Delete("c:\\Filechecker\\inboxbackup\\" + basename);
    }
    // copy file to backup folder - no "file already exists errors as check above has removed any existing files

    File.Copy(filename, "c:\\Filechecker\\inboxbackup\\" + basename);

     

    Ray..

     

    Wednesday, April 23, 2008 11:05 AM
  •  

    very odd. Are you sure "basename" file is already closed, if you are writing to it within your application?

     

    To check if a file exists:

     

    if (System.IO.File.Exists("filename"))

    {

       //delete

       System.IO.File.Delete("filename"); //try/catch exception handling needs to be implemented

    }

    Monday, April 21, 2008 11:31 PM
    Moderator

All replies

  •  

    very odd. Are you sure "basename" file is already closed, if you are writing to it within your application?

     

    To check if a file exists:

     

    if (System.IO.File.Exists("filename"))

    {

       //delete

       System.IO.File.Delete("filename"); //try/catch exception handling needs to be implemented

    }

    Monday, April 21, 2008 11:31 PM
    Moderator
  • Please try this one.

     

    if (System.IO.File.Exists("filepath"))

    System.IO.File.Copy("newfilename", "filepath", true);

    else

    {

    System.IO.File.Create("path");

    System.IO.File.Move("newfilename", "path");

    }

     

    Tuesday, April 22, 2008 1:27 AM
  • Thx for both your help..

    It helped me come up with the following

     


    // check if file already exists in inboxbackup if it does then delete
    if (File.Exists("c:\\Filechecker\\inboxbackup\\" + basename) )
    {
    File.Delete("c:\\Filechecker\\inboxbackup\\" + basename);
    }
    // copy file to backup folder - no "file already exists errors as check above has removed any existing files

    File.Copy(filename, "c:\\Filechecker\\inboxbackup\\" + basename);

     

    Ray..

     

    Wednesday, April 23, 2008 11:05 AM