簡體   English   中英

如何將文件復制到另一個路徑?

[英]How to copy a file to another path?

我需要將文件復制到另一個路徑,將原始文件留在原處。

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

FileInfo 的 CopyTo 方法會起作用嗎?

看看File.Copy()

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

所以像

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

另請參見如何:復制、刪除和移動文件和文件夾(C# 編程指南)

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

使用此方法允許或防止覆蓋現有文件。 默認情況下,使用 CopyTo 方法可防止覆蓋現有文件。

所有其他響應都是正確的,但由於您要求FileInfo ,這里有一個示例:

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

我試圖將一個 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 函數中調用了這個函數,我認為你不需要看到它。 有效。 希望這可以幫助。

你也可以使用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 在將源文件復制到新位置后希望對其重命名,則可以調整重命名代碼。

File::Copy 會將文件復制到目標文件夾,而 File::Move 可以移動和重命名文件。

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

這就是我將測試文件從下載移動到桌面所做的工作。 我希望它有用。

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

老問題,但我想添加完整的控制台應用程序示例,考慮到您擁有給定文件夾的文件和適當的權限,這里是代碼

 class Program
 {
    static void Main(string[] args)
    {
        //path of file
        string pathToOriginalFile = @"E:\C-sharp-IO\test.txt";

        
        //duplicate file path 
        string PathForDuplicateFile = @"E:\C-sharp-IO\testDuplicate.txt";
         
          //provide source and destination file paths
        File.Copy(pathToOriginalFile, PathForDuplicateFile);

        Console.ReadKey();

    }
}

來源: C# 中的文件 I/O(使用 C# 讀取、寫入、刪除、復制文件)

復制文件夾我使用兩個文本框來知道文件夾的位置和花葯文本框來知道要復制的文件夾是什么,這是代碼

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM