Forum guidelines
AuthorQuestion
Copy directory with only specific extension files
Posted By darma teja on 25 Nov 2012
Hi,

I have problem in copying only specific extension.

My code copy to folder is:

 Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(oldpath, newpath);

But I want to copy only specific file extension.


Thanks,

Darma



AuthorReply
Vulpes
  • 0
  • 0
accepted
Re: Copy directory with only specific extension files
Posted By Vulpes on 25 Nov 2012   Accepted Answer
AFAIK, there's no method in the .NET Framework or the VB runtime library which can do this 'out of the box'. We'll therefore need to write a custom method:

using System;
using System.IO;

class Test
{
    static void Main()
    {
       string sourceDir = "c:\\whatever";
       string destDir = "c:\\whatever2";
       CopyDirectory(sourceDir, destDir, "xls");
    }

    static void CopyDirectory(string sourceDir, string destDir, string extension)
    {
       string[] filePaths = Directory.GetFiles(sourceDir, "*." + extension);
     
       if (!Directory.Exists(destDir))
       {
          Directory.CreateDirectory(destDir);
       }
  
       foreach(string filePath in filePaths)
       {
          string fileName = Path.GetFileName(filePath);
          File.Copy(filePath, String.Format("{0}\\{1}", destDir, fileName));
       }
    }
}



 

SPONSORED BY

Custom Software Development
MCN is your source for developing solutions involving websites, mobile apps, cloud-computing, databases, BI, back-end services and processes and client-server applications.