简体   繁体   English

使用C#中的filepath复制文件夹中的文件

[英]Copy file in folder using filepath in C#

I have the [Source:(path)] of file which is to be copied at location [DestinationC:\\MyFiles\\TempFolder] 我有[源:(路径)]文件,要在[DestinationC:\\ MyFiles \\ TempFolder]复制

Suppose path is C:\\Documents and Settings\\MyName\\My Documents\\xyz.doc I want xyz.doc to be copied at C:\\MyFiles\\TempFolder\\ iethe location becomesC:\\MyFiles\\TempFolder\\xyz.doc 假设路径是C:\\ Documents and Settings \\ MyName \\ My Documents \\ xyz.doc我希望在C:\\ MyFiles \\ TempFolder \\ iet复制位置xyz.doc成为C:\\ MyFiles \\ TempFolder \\ xyz.doc

is it possible to rename file while coping it to destination folder? 是否可以在将文件复制到目标文件夹时重命名文件?

Thanking you... 感谢您...

All you need is System.IO.File.Copy() : http://msdn.microsoft.com/en-us/library/c6cfw35a.aspx 所有你需要的是System.IO.File.Copy()http//msdn.microsoft.com/en-us/library/c6cfw35a.aspx

File.Copy("C:\Documents and Settings\MyName\My Documents\xyz.doc", "C:\MyFiles\TempFolder\" + newFilenName);

(Be careful with \\ in the strings above, they should be escaped \\\\ ) (在上面的字符串中要注意\\它们应该被转义\\\\

Copying is creating a new file with the same contents of the old one, so the new name doesn't have to be anything like the old name. 复制正在创建一个与旧文件具有相同内容的新文件,因此新名称不必与旧名称相同。 In fact, if you consider the full path as part of the filename, you can see that the source and destination are different from the start, even if you don't change xyz.doc . 实际上,如果将完整路径视为文件名的一部分,即使不更改xyz.doc ,也可以看到源和目标与开头不同。

Well... you can use Copy, but you'll need to check if the directory is present: 嗯......你可以使用Copy,但是你需要检查目录是否存在:

string file = @"C:\Documents and Settings\MyName\My Documents\xyz.doc";
string destination = @"C:\MyFiles\TempFolder";

if(!System.IO.Directory.Exists(destination))
{
 System.IO.Directory.CreateDirectory(destination);
}

destination = System.IO.Path.Combine(destination, System.IO.Path.GetFileName(file));
System.IO.File.Copy(file, destination);

Changed the code to reflect your example. 更改了代码以反映您的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM