简体   繁体   中英

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]

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

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

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 .

Well... you can use Copy, but you'll need to check if the directory is present:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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