locked
Move files from one directory to another directory using c# and accept arguments RRS feed

  • Question

  • Hi,

    I need to create a console app using c# to move files from one directory to another.

    eg: c:\mytest\*.csv to D:\apps

    All the examples shows iterating through files and copy a file for all files OR create directory.

    I don't need to create a directory. Source and Target directories already exist.

    This console app gets executed from SSIS packages. So, the app also should be able to

        a) accept arguments when called from SSIS

        b) Return success or failure

        c) If errored, error number or reason.

    Please point me to right source.

    Thank You

    Monday, August 29, 2016 1:51 PM

Answers

  • Hi,

    I need to create a console app using c# to move files from one directory to another.

    eg: c:\mytest\*.csv to D:\apps

    All the examples shows iterating through files and copy a file for all files OR create directory.

    I don't need to create a directory. Source and Target directories already exist.

    This console app gets executed from SSIS packages. So, the app also should be able to

        a) accept arguments when called from SSIS

        b) Return success or failure

        c) If errored, error number or reason.

    Please point me to right source.

    Thank You

    Hi Spunny,

    That is an easy task, achieved with System.IO classes. This snippet from MSDN illustrates how to do it without UI, just like what you need:

    // Simple synchronous file copy operations with no user interface.
    // To run this sample, first create the following directories and files:
    // C:\Users\Public\TestFolder
    // C:\Users\Public\TestFolder\test.txt
    // C:\Users\Public\TestFolder\SubDir\test.txt
    public class SimpleFileCopy
    {
        static void Main()
        {
            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!");
            }
    
            // Keep console window open in debug mode.
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
    }

    Please let me know if this answers your question.

    Thanks,


    My Technet Articles

    If you like this or another reply, vote it up!
    If you think this or another reply answers the original question, mark it or propose it as an answer.


    Mauricio Feijo
    www.mauriciofeijo.com

    Tuesday, August 30, 2016 8:45 PM

All replies

  • Use the File.Move Method (String, String). Or take a look at the File System Task in SSIS.
    Monday, August 29, 2016 2:06 PM
  • Stefan thank you for quick response. This code will be used by many packages. So, I am planning not to do in SSIS. That is the reason, creating console app. If needed other processes can use it too.

    File.Move method moves particular file. I want to move ALL FILES from source to target with out iterating through each file

    Thank You

    Monday, August 29, 2016 2:15 PM
  • You really don't need to create a console app for this. There are already plenty of apps that will do this. Look into Robocopy or similar if you're interested. You are going to have the same deployment issues (getting it on each machine) as your own console app but: 1) it is already written and tested, 2) you don't have to manage the source code.

    Personally I would recommend that you take a look at Powershell to do this. There is no benefit in a console app for something trivial like this and the PS script can handle any sort of batch operations and parameterization you want.

    Michael Taylor
    http://www.michaeltaylorp3.net

    Monday, August 29, 2016 3:06 PM
  • Hi Taylor,

    Thank you for the response. I don't know how to write Powershell script in a file that accepts parameters and moves files from one directory to another. Can you please direct me to the proper resource or can you provide the code.

    Thank You

    Tuesday, August 30, 2016 3:25 AM
  • Powershell scripts allow you to use the param value to specify parameters to a script. This is a pretty good Q&A about them. You should use the Powershell ISE that ships with Windows to edit the script so you can more easily debug it.

    But since you're already in SSIS I'm not really sure why you wouldn't want to simply use the File System task as already mentioned. Is it because you'll have to use several tasks to get the behavior you want? If so then take a look at creating a custom SSIS task. It isn't trivial, Powershell would be easier, but custom tasks fit neatly into the SSIS designer and are useful for creating reusable pieces of functionality.  It will also resolve the whole issue of where to put the PS script (or a console app for that matter) so that all your packages can access it. I blogged about how to write one a while back if you're interested.

    Michael Taylor
    http://www.michaeltaylorp3.net

    Tuesday, August 30, 2016 1:50 PM
  • No Michael. The same code need to be used by multiple packages. So, don't want to repeat the code in each and every package.

    Tuesday, August 30, 2016 7:37 PM
  • Also, do not want to sign the assembly or register it in GAC.
    Tuesday, August 30, 2016 7:47 PM
  • "do not want to sign the assembly or register it in GAC"

    Why? The custom task is the cleaner, more maintainable approach to me. You could literally drag and drop it from the designer, set the parameters as you need and move on. Deployment requires running a script the first time and you're done.

    If you don't want to go that route then Powershell would require that you use the Execute Process task. It is discussed here. The only difference between PS and your own console app is maintainability and turnaround. Functionally they will behave the same. But, like a console app, you have to figure out where to store the script. Since SSIS runs as a service under a service account it doesn't have access to the same stuff you do. You will have to deploy your script to each SSIS machine although you might be able to use UNC. Security may get in the way here. You'll also have to get the task to recognize any parameters you want to pass. If you're building the list of files up in the workflow then this may require that you use a script task anyway. If you end up going that route then you'll have to do that in all your packages.

    Tuesday, August 30, 2016 8:21 PM
  • Hi,

    I need to create a console app using c# to move files from one directory to another.

    eg: c:\mytest\*.csv to D:\apps

    All the examples shows iterating through files and copy a file for all files OR create directory.

    I don't need to create a directory. Source and Target directories already exist.

    This console app gets executed from SSIS packages. So, the app also should be able to

        a) accept arguments when called from SSIS

        b) Return success or failure

        c) If errored, error number or reason.

    Please point me to right source.

    Thank You

    Hi Spunny,

    That is an easy task, achieved with System.IO classes. This snippet from MSDN illustrates how to do it without UI, just like what you need:

    // Simple synchronous file copy operations with no user interface.
    // To run this sample, first create the following directories and files:
    // C:\Users\Public\TestFolder
    // C:\Users\Public\TestFolder\test.txt
    // C:\Users\Public\TestFolder\SubDir\test.txt
    public class SimpleFileCopy
    {
        static void Main()
        {
            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!");
            }
    
            // Keep console window open in debug mode.
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
    }

    Please let me know if this answers your question.

    Thanks,


    My Technet Articles

    If you like this or another reply, vote it up!
    If you think this or another reply answers the original question, mark it or propose it as an answer.


    Mauricio Feijo
    www.mauriciofeijo.com

    Tuesday, August 30, 2016 8:45 PM
  • This is even more to the point, silently moving all files from a directory like you asked:

    // Simple synchronous file move operations with no user interface.
    public class SimpleFileMove
    {
        static void Main()
        {
            string sourceFile = @"C:\Users\Public\public\test.txt";
            string destinationFile = @"C:\Users\Public\private\test.txt";
    
            // To move a file or folder to a new location:
            System.IO.File.Move(sourceFile, destinationFile);
    
            // To move an entire directory. To programmatically modify or combine
            // path strings, use the System.IO.Path class.
            System.IO.Directory.Move(@"C:\Users\Public\public\test\", @"C:\Users\Public\private");
        }
    }

    From MSDN


    My Technet Articles

    If you like this or another reply, vote it up!
    If you think this or another reply answers the original question, mark it or propose it as an answer.


    Mauricio Feijo
    www.mauriciofeijo.com

    Tuesday, August 30, 2016 8:48 PM
  • Because our production servers are in DMZ and with parent company and we need to go through a lot of steps to justify and so many other issues.
    Wednesday, August 31, 2016 3:00 AM
  • Then use Powershell (ideally) or write your own console app. I suspect however that you'll have to revisit this solution down the road.
    Wednesday, August 31, 2016 4:01 AM
  • Spunny,

    Did you attempt my solution? Did it work? If not, what was the problem?


    My Technet Articles

    If you like this or another reply, vote it up!
    If you think this or another reply answers the original question, mark it or propose it as an answer.


    Mauricio Feijo
    www.mauriciofeijo.com

    Wednesday, August 31, 2016 2:53 PM
  • Hi Spunny,

    Thank you for posting here.

    If your problem has been solved, I will mark reply of Mauricio Feijo as answer.

    If it does not solve, please unmark.

    Thanks for your understanding and cooperation.

    Best Regards,

    Wendy


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.


    Wednesday, September 21, 2016 1:40 AM