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:开发者_StackOverflow社区\Documents and Settings\MyName\My Documents\xyz.doc I want xyz.doc to be copied at C:\MyFiles\TempFolder\ i.e.the 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.
精彩评论