Tuesday, October 20, 2015

Copy sub folders and files by using X++

As far I know, In AX 2012, there is no direct functionality available to copy the files and sub directories. First we can create the sub directories recursively and copy the all source files to destination path.

I have created simple job for your reference.

static void Hari_CopyFolderAndFiles(Args _args)
{   
    str             source = @"F:\AX\Hari\Test";
    str             dest = @"F:\AX\Hari\Destination";
    str             tempFolderPath;
    System.String[] directories = System.IO.Directory::GetDirectories(source, "*.*", System.IO.SearchOption::AllDirectories);
    int             folderCount = directories.get_Length();
    int             currentFolderCount;
    void copyAllFiles(str sourceFolder, str destFolder)
    {
        str                 tempDestFileName;
        System.String[]     filePaths = System.IO.Directory::GetFiles(sourceFolder, "*.*", System.IO.SearchOption::AllDirectories); //get listing of all files within the folder
        System.IO.FileInfo  sourceFile;
        int                 fileCount = filepaths.get_Length();
        int                 currentFileCount;
    
        for(currentFileCount = 0; currentFileCount < fileCount ; ++currentFileCount)
        {
            sourceFile = new System.IO.FileInfo(filepaths.GetValue(currentFileCount));
            tempDestFileName = strReplace(filepaths.GetValue(currentFileCount), sourceFolder, destFolder);
            //Copy file
            sourceFile.CopyTo(tempDestFileName, true);           
        }
    }
  
    //Create sub directories
    for(currentFolderCount = 0; currentFolderCount < folderCount ; ++currentFolderCount)
    {
        tempFolderPath = strReplace(directories.GetValue(currentFolderCount), source, dest);
        if(!System.IO.Directory::Exists(tempFolderPath))
        {
            System.IO.Directory::CreateDirectory(tempFolderPath);
        }
    }
   
    //Copy all files include sub directory files
    copyAllFiles(source, dest);
    info('Success');