Click here to Skip to main content
15,885,914 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
i am using this function in the timer
every tick it will copy the files to the target path but by this it is overwriting the existing files so can any one help me

What I have tried:

<pre> public static void Copy(string sourceDirectory, string targetDirectory)
    {
        DirectoryInfo diSource = new DirectoryInfo(sourceDirectory);
        DirectoryInfo diTarget = new DirectoryInfo(targetDirectory);

        CopyAll(diSource, diTarget);
    }

    public static void CopyAll(DirectoryInfo source, DirectoryInfo target)
    {
        Directory.CreateDirectory(target.FullName);

        // Copy each file into the new directory.
        foreach (FileInfo fi in source.GetFiles())
        {
            Console.WriteLine(@"Copying {0}\{1}", target.FullName, fi.Name);
            fi.CopyTo(Path.Combine(target.FullName, fi.Name), true);
        }

        // Copy each subdirectory using recursion.
        foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
        {
            DirectoryInfo nextTargetSubDir =
                target.CreateSubdirectory(diSourceSubDir.Name);
            CopyAll(diSourceSubDir, nextTargetSubDir);
        }
    }

    public static void Main()
    {
        string sourceDirectory = @"F:\\payload_Data\\File_Splitted_1";
        string targetDirectory = @"c:\targetDirectory";

        Copy(sourceDirectory, targetDirectory);
    }

    // Output will vary based on the contents of the source directory.
}
Posted
Updated 23-May-17 3:31am
Comments
[no name] 23-May-17 9:26am    
So check to see if the file exists and provide an alternate filename if it does. Or, rename the existing file if you need to keep it.
Veerendra-13142768 23-May-17 9:35am    
ya after one timer tick it should copy the same files so same file name will be their.

1 solution

It's not complex:
if (File.Exists(originalPath))
    {
    File.Move(originalPath, newPath);
    }
 
Share this answer
 
Comments
Veerendra-13142768 23-May-17 9:33am    
but it is a continuous process so every time how can we give a new path
OriginalGriff 23-May-17 9:39am    
That's going to depend on you and what you want to call the file you are about to replace!

Me? I'd probably tag them with the date and time: a prefix such as "20170503143718." means that the "backups" remain in chronological order - but you may have a scheme in mind. We don't know what you want!
Maciej Los 23-May-17 11:50am    
5 tow times: 1) for the answer and 2) for the comment ;)

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