Search code examples
c#filecopy

how to copy a file from current folder to another folder in C#


How can I copy test.pdf from current folder to C:exfolder I know the siple copy way in C# But I want the code which works for any folders which the exe file in in it . I was confuised beacuse when I wanted to use current folder path visual studio 2008 erros beacaus I used :

string fileName = "test_log.LDF";
            string sourcePath = @ + Application.StartupPath;
            string targetPath = @"C:\honar2";

            // 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);
            }
            System.IO.File.Copy(sourceFile, destFile, true);

Solution

  • You can get directory for the exe file using the System.Environment.CurrentDirectory, then use the System.IO.File.Copy method to copy that file to any destination. Also for getting the current directory you may want to see this