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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1979920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:22:37  来源:igfitidea点击:

How to copy a file to another path?

c#file-io

提问by mrblah

I need to copy a file to another path, leaving the original where it is.

我需要将文件复制到另一个路径,将原始文件留在原处。

I also want to be able to rename the file.

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

Will FileInfo's CopyTo method work?

FileInfo 的 CopyTo 方法会起作用吗?

回答by Adriaan Stander

Have a look at File.Copy()

看看File.Copy()

Using File.Copy you can specify the new file name as part of the destination string.

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

So something like

所以像

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

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

另请参见如何:复制、删除和移动文件和文件夹(C# 编程指南)

回答by Thorsten Dittmar

You could also use File.Copyto copy and File.Moveto rename it afterwords.

您还可以使用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!");

EDIT
Commented out the "rename" code, because File.Copycan already copy and rename in one step, as astander noted correctly in the comments.

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

However, the rename code could be adapted if the OP desired to rename the source file after it has been copied to a new location.

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

回答by A9S6

File::Copy will copy the file to the destination folder and File::Move can both move and rename a file.

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

回答by Rubens Farias

Yes. It will work: FileInfo.CopyTo Method

是的。它将起作用:FileInfo.CopyTo 方法

Use this method to allow or prevent overwriting of an existing file. Use the CopyTo method to prevent overwriting of an existing file by default.

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

All other responses are correct, but since you asked for FileInfo, here's a sample:

所有其他回答都是正确的,但由于您要求FileInfo,这里有一个示例:

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

回答by Sajib Mahmood

I tried to copy an xml file from one location to another. Here is my code:

我试图将一个 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);
}

Then I called this function inside a timer_elapsed function of certain interval which I think you don't need to see. It worked. Hope this helps.

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

回答by Abdelrhman Khalil

TO Copy The Folder I Use Two Text Box To Know The Place Of Folder And Anther Text Box To Know What The Folder To Copy It And This Is The Code

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

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);

        }

回答by user2673536

This is what I did to move a test file from the downloads to the desktop. I hope its useful.

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

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);
        }
    }        

回答by Kiran k g

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);

回答by s123

File.Move(@"c:\filename", @"c:\filenamet\filename.txt");