【发布时间】:2010-12-31 02:20:00
【问题描述】:
我需要将文件复制到另一个路径,将原始文件保留在原处。
我还希望能够重命名文件。
FileInfo 的 CopyTo 方法会起作用吗?
【问题讨论】:
-
您要重命名原始文件还是新复制的文件?
我需要将文件复制到另一个路径,将原始文件保留在原处。
我还希望能够重命名文件。
FileInfo 的 CopyTo 方法会起作用吗?
【问题讨论】:
使用 File.Copy,您可以将新文件名指定为目标字符串的一部分。
类似
File.Copy(@"c:\test.txt", @"c:\test\foo.txt");
另见How to: Copy, Delete, and Move Files and Folders (C# Programming Guide)
【讨论】:
@ 的目的是什么?
@ 用于声明逐字字符串。检查What is the difference between a regular string and a verbatim string?
是的。它将起作用:FileInfo.CopyTo Method
使用此方法允许或防止覆盖现有文件。默认情况下使用 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 已经可以一步复制和重命名,正如 cmets 中正确指出的那样。
但是,如果 OP 希望在将源文件复制到新位置后重命名源文件,则可以调整重命名代码。
【讨论】:
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);
【讨论】:
File::Copy 会将文件复制到目标文件夹,并且 File::Move 可以移动和重命名文件。
【讨论】:
这就是我将测试文件从下载文件移动到桌面的方法。 我希望它有用。
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();
}
}
【讨论】:
要复制文件夹,我使用两个文本框来知道文件夹的位置和另一个文本框来知道要复制它的文件夹,这是代码
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");
【讨论】: