Click here to Skip to main content
15,907,236 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a directory path like this \\servername\DirectoryName\<jobcard>_<programname>_<date>.csv and in that there are multiple csv files of similar name pattern now I want to copy that from one directory to another in c#.Can anyone help me out with this., I want to write it as windows service form.
Posted
Updated 16-Oct-12 1:56am
v2

string fileName = "test.txt";
string sourcePath = @"C:\Users\Public\TestFolder";
string targetPath =  @"C:\Users\Public\TestFolder\SubDir";

// Use Path class to manipulate file and directory paths.
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);

// To copy a folder's contents to a new location:
// Create a new target folder, if necessary.
if (!System.IO.Directory.Exists(targetPath))
{
    System.IO.Directory.CreateDirectory(targetPath);
}

// To copy a file to another location and
// overwrite the destination file if it already exists.
System.IO.File.Copy(sourceFile, destFile, true);

// To copy all the files in one directory to another directory.
// Get the files in the source folder. (To recursively iterate through
// all subfolders under the current directory, see
// "How to: Iterate Through a Directory Tree.")
// Note: Check for target path was performed previously
//       in this code example.
if (System.IO.Directory.Exists(sourcePath))
{
    string[] files = System.IO.Directory.GetFiles(sourcePath);

    // Copy the files and overwrite destination files if they already exist.
    foreach (string s in files)
    {
        // Use static Path methods to extract only the file name from the path.
        fileName = System.IO.Path.GetFileName(s);
        destFile = System.IO.Path.Combine(targetPath, fileName);
        System.IO.File.Copy(s, destFile, true);
    }
}
else
{
    Console.WriteLine("Source path does not exist!");
}
 
Share this answer
 
C#
string Source = "<source path>";
string Destination = "<destination path>";
FileInfo[] files = new DirectoryInfo(Source).GetFiles();
foreach (FileInfo i in files)
if (i.Name.EndsWith("_.csv"))
File.Copy(i.FullName, Destination + i.Name);
 
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