Click here to Skip to main content
15,905,322 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Replace the existing file with old file in asp.net using c#.

My code as follows;

string filepath = Application.StartupPath + "\\Preseaintake\\newtest.xls";
string filepath1 = Application.StartupPath + "\\Preseaintake\\test.xls";
string filepath2 = Application.StartupPath + "\\Preseaintake\\backup.xls";

if (System.IO.File.Exists(filepath))
File.Replace(filepath1, filepath, filepath2);

xlWorkBook.SaveAs(filepath1, misvalue, misvalue, misvalue, misvalue, misvalue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misvalue, misvalue,
misvalue, misvalue, misvalue);
xlWorkBook.Close(true, misvalue, misvalue);


i replacing existing file with new file.

for that i written a code above. But when i run shows error as follows;

unable to find a specified file.

The error shows in below line as follows;

File.Replace(filepath1, filepath, filepath2);


from my above code what is the mistake i madde.

please help me.

Regards,
Narasiman P.
Posted
Comments
Sergey Alexandrovich Kryukov 14-Mar-14 23:37pm    
One of the files is not found. Check up file names.
—SA

1 solution


First, rename your variables so that the names connote meaning.



Use a try-catch block to capture the exception.



The following rewrites your code. When the exception occurs, you will be provided with an indication as to what caused the error. My guess is that your source file does not exist. This in turn implies that your test for existence needs to be made against the source rather than the destination (as you have now).


C#
string destination_filename = Application.StartupPath + "\\Preseaintake\\newtest.xls";
string source_filename = Application.StartupPath + "\\Preseaintake\\test.xls";
string backup_filename = Application.StartupPath + "\\Preseaintake\\backup.xls";

try
    {
    if ( File.Exists ( destination_filename ) )
        {
        File.Replace( source_filename, 
                      destination_filename, 
                      backup_filename );
        MessageBox.Show ( "Replaced" );
        }
    }
catch ( Exception ex )
    {
    MessageBox.Show ( ex.Message +
                      Environment.NewLine +
                      ex.StackTrace );
    }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900