如何将文件复制到另一个路径?

问题描述 投票:45回答:9

我需要将文件复制到另一个路径,将原始文件保留在原来的位置。

我也希望能够重命名该文件。

FileInfo的CopyTo方法会起作用吗?

c# file-io
9个回答
74
投票

看看File.Copy()

使用File.Copy,您可以将新文件名指定为目标字符串的一部分。

所以像

File.Copy(@"c:\test.txt", @"c:\test\foo.txt");

另见How to: Copy, Delete, and Move Files and Folders (C# Programming Guide)


7
投票

我试图将xml文件从一个位置复制到另一个位置。这是我的代码:

public void SaveStockInfoToAnotherFile()
{
    string sourcePath = @"C:\inetpub\wwwroot";
    string destinationPath = @"G:\ProjectBO\ForFutureAnalysis";
    string sourceFileName = "startingStock.xml";
    string destinationFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".xml"; // Don't mind this. I did this because I needed to name the copied files with respect to time.
    string sourceFile = System.IO.Path.Combine(sourcePath, sourceFileName);
    string destinationFile = System.IO.Path.Combine(destinationPath, destinationFileName);

    if (!System.IO.Directory.Exists(destinationPath))
       {
         System.IO.Directory.CreateDirectory(destinationPath);
       }
    System.IO.File.Copy(sourceFile, destinationFile, true);
}

然后我在一定间隔的timer_elapsed函数中调用了这个函数,我认为你不需要看。有效。希望这可以帮助。


6
投票

是。它会起作用:FileInfo.CopyTo Method

使用此方法允许或阻止覆盖现有文件。使用CopyTo方法可以防止默认情况下覆盖现有文件。

所有其他答案都是正确的,但既然你要求FileInfo,这里是一个样本:

FileInfo fi = new FileInfo(@"c:\yourfile.ext");
fi.CopyTo(@"d:\anotherfile.ext", true); // existing file will be overwritten

4
投票

你也可以使用File.Copy复制和File.Move重命名后。

// Copy the file (specify true or false to overwrite or not overwrite the destination file if it exists.
File.Copy(mySourceFileAndPath, myDestinationFileAndPath, [true | false]);

// EDIT: as "astander" notes correctly, this step is not necessary, as File.Copy can rename already...
//       However, this code could be adapted to rename the original file after copying
// Rename the file if the destination file doesn't exist. Throw exception otherwise
//if (!File.Exists(myRenamedDestinationFileAndPath))
//    File.Move(myDestinationFileAndPath, myRenamedDestinationFileAndPath);
//else
//    throw new IOException("Failed to rename file after copying, because destination file exists!");

编辑 注释掉“重命名”代码,因为File.Copy已经可以一步复制和重命名,正如旁观者在评论中正确指出的那样。

但是,如果OP希望在将源文件复制到新位置后重命名,则可以调整重命名代码。


2
投票

File :: Copy会将文件复制到目标文件夹,File :: Move可以移动和重命名文件。


2
投票
string directoryPath = Path.GetDirectoryName(destinationFileName);

// If directory doesn't exist create one
if (!Directory.Exists(directoryPath))
{
DirectoryInfo di = Directory.CreateDirectory(directoryPath);
}

File.Copy(sourceFileName, destinationFileName);

0
投票

这就是我将测试文件从下载移动到桌面所做的工作。我希望它有用。

private void button1_Click(object sender, EventArgs e)//Copy files to the desktop
    {
        string sourcePath = @"C:\Users\UsreName\Downloads";
        string targetPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
        string[] shortcuts = {
            "FileCopyTest.txt"};

        try
        {
            listbox1.Items.Add("Starting: Copy shortcuts to dektop.");
            for (int i = 0; i < shortcuts.Length; i++)
            {
                if (shortcuts[i]!= null)
                {
                    File.Copy(Path.Combine(sourcePath, shortcuts[i]), Path.Combine(targetPath, shortcuts[i]), true);                        
                    listbox1.Items.Add(shortcuts[i] + " was moved to desktop!");
                }
                else
                {
                    listbox1.Items.Add("Shortcut " + shortcuts[i] + " Not found!");
                }
            }
        }
        catch (Exception ex)
        {
            listbox1.Items.Add("Unable to Copy file. Error : " + ex);
        }
    }        

-1
投票

复制文件夹我使用两个文本框来知道文件夹和花药文本框的位置知道什么文件夹复制它这就是代码

MessageBox.Show("The File is Create in The Place Of The Programe If you Don't Write The Place Of copy And You write Only Name Of Folder");// It Is To Help The User TO Know
          if (Fromtb.Text=="")
        {
            MessageBox.Show("Ples You Should Write All Text Box");
            Fromtb.Select();
            return;
        }
        else if (Nametb.Text == "")
        {
            MessageBox.Show("Ples You Should Write The Third Text Box");
            Nametb.Select();
            return;
        }
        else if (Totb.Text == "")
        {
            MessageBox.Show("Ples You Should Write The Second Text Box");
            Totb.Select();
            return;
        }

        string fileName = Nametb.Text;
        string sourcePath = @"" + Fromtb.Text;
        string targetPath = @"" + Totb.Text;


        string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
        string destFile = System.IO.Path.Combine(targetPath, fileName);


        if (!System.IO.Directory.Exists(targetPath))
        {
            System.IO.Directory.CreateDirectory(targetPath);
            //when The User Write The New Folder It Will Create 
            MessageBox.Show("The File is Create in "+" "+Totb.Text);
        }


        System.IO.File.Copy(sourceFile, destFile, true);


        if (System.IO.Directory.Exists(sourcePath))
        {
            string[] files = System.IO.Directory.GetFiles(sourcePath);


            foreach (string s in files)
            {
                fileName = System.IO.Path.GetFileName(s);
                destFile = System.IO.Path.Combine(targetPath, fileName);
                System.IO.File.Copy(s, destFile, true);

            }
            MessageBox.Show("The File is copy To " + Totb.Text);

        }

-2
投票
File.Move(@"c:\filename", @"c:\filenamet\filename.txt");
© www.soinside.com 2019 - 2024. All rights reserved.