Anuya
Anuya

Reputation: 8350

How to copy a folder from one one path and paste it to another path using C#?

The copied original folder should be pasted inside folder named with today's date like "220310"

Like.....

Original folder : c://Org/AbcFolder

Destination folder : D://Dest/220310/AbcFolder

Upvotes: 0

Views: 6908

Answers (3)

friendchp
friendchp

Reputation: 11

You can get date time with this :

DateTime dtnow = DateTime.Now;
string strDate=dtnow.Day.ToString()+dtnow.Month.ToString()+dtnow.Year.ToString();

And for copy the directory to another see this CodeProject article: Function to copy a directory to another place (nothing fancy)

Upvotes: 0

Anuya
Anuya

Reputation: 8350

private static bool CopyDirectory(string SourcePath, string DestinationPath, bool overwriteexisting)
        {
            bool ret = true;
            try
            {
                SourcePath = SourcePath.EndsWith(@"\") ? SourcePath : SourcePath + @"\";
                DestinationPath = DestinationPath.EndsWith(@"\") ? DestinationPath : DestinationPath + @"\";

                if (Directory.Exists(SourcePath))
                {
                    if (Directory.Exists(DestinationPath) == false)
                        Directory.CreateDirectory(DestinationPath);

                    foreach (string fls in Directory.GetFiles(SourcePath))
                    {
                        FileInfo flinfo = new FileInfo(fls);
                        flinfo.CopyTo(DestinationPath + flinfo.Name, overwriteexisting);
                    }
                    foreach (string drs in Directory.GetDirectories(SourcePath))
                    {
                        DirectoryInfo drinfo = new DirectoryInfo(drs);
                        if (CopyDirectory(drs, DestinationPath + drinfo.Name, overwriteexisting) == false)
                            ret = false;
                    }
                    Directory.CreateDirectory(DI_Target + "//Database");
                }
                else
                {
                    ret = false;
                }
            }
            catch (Exception ex)
            {
                ret = false;
            }
            return ret;
        }

Upvotes: 3

Axarydax
Axarydax

Reputation: 16603

Basically you'd use

var files = Directory.GetFiles(originalFolder,"*.*",SearchOption.AllDirectories) 

to get all files you want to copy, then create target directory by

Directory.Create(destinationFolder)

and loop over original filenames (in files), use FileInfo class to get path of original files, and File.Copy() to copy files to their new location. All of these classes are in System.IO namespace.

Upvotes: 0

Related Questions