-1

I want to know how to copy a file, not regarding it's type, pptx docx txt, and paste it in another address of the directory in C#. I assume that the File.Copy function is only available for .txt file, and it is not a file copy and paste, it is a contents copy and paste.

Thank you.

Leo Park
  • 1
  • 1

1 Answers1

0

This code is from the Microsoft docs, apparently it can copy .jpg files and if it can it should be able to copy all file types

string sourceDir = @"c:\current";
string backupDir = @"c:\archives\2008";

try
{
    string[] picList = Directory.GetFiles(sourceDir, "*.jpg");
    string[] txtList = Directory.GetFiles(sourceDir, "*.txt");

    // Copy picture files.
    foreach (string f in picList)
    {
        // Remove path from the file name.
        string fName = f.Substring(sourceDir.Length + 1);

        // Use the Path.Combine method to safely append the file name to the path.
        // Will overwrite if the destination file already exists.
        File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), true);
    }

    // Copy text files.
    foreach (string f in txtList)
    {

        // Remove path from the file name.
        string fName = f.Substring(sourceDir.Length + 1);

        try
        {
            // Will not overwrite if the destination file already exists.
            File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName));
        }

        // Catch exception if the file was already copied.
        catch (IOException copyError)
        {
            Console.WriteLine(copyError.Message);
        }
    }

    // Delete source files that were copied.
    foreach (string f in txtList)
    {
        File.Delete(f);
    }
    foreach (string f in picList)
    {
        File.Delete(f);
    }
}

catch (DirectoryNotFoundException dirNotFound)
{
    Console.WriteLine(dirNotFound.Message);
}

Source: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.copy?view=net-6.0#system-io-file-copy(system-string-system-string-system-boolean)

  • Thank you so much. Actually this is very easy process, but because of my lack of understanding in file and data, I wasn't able to do this correctly. I selectively used the code and got the job done. Thank you so much. – Leo Park Jun 25 '22 at 10:21