C # copy files and copy folder instance code C # copy files

Source: Internet
Author: User

The original file path is fileoldpath;
New file path: filenewpath,
Then you can use
File. Move (fileoldpath, filenewpath)
Or file. Copy (fileoldpath, filenewpath)
Note that the path here is the folder path + file name, which can be implemented using path. Combine ().

C # copy a folder

The Directory class contains the createdirectory, move, and delete methods, but there is no copy method-_-. Below we will write a class for implementation, the idea is to recursively copy the files in the specified folder and Its subfolders to the target Folder:

Program Code
Using system;
Using system. Data;
Using system. configuration;
Using system. Web;
Using system. Web. Security;
Using system. Web. UI;
Using system. Web. UI. webcontrols;
Using system. Web. UI. webcontrols. webparts;
Using system. Web. UI. htmlcontrols;
Using system. IO;
/// <Summary>
/// Summary of mydirectory
/// </Summary>
Public class mydirectory
{
/// <Summary>
/// Copy a folder
/// </Summary>
/// <Param name = "sourcedirname"> original path </param>
/// <Param name = "destdirname"> target path </param>
/// <Returns> </returns>
Public static void copy (string sourcedirname, string destdirname)
{
If (sourcedirname. substring (sourcedirname. Length-1 )! = "\\")
{
Sourcedirname = sourcedirname + "\\";
}
If (destdirname. substring (destdirname. Length-1 )! = "\\")
{
Destdirname = destdirname + "\\";
}
If (directory. exists (sourcedirname ))
{
If (! Directory. exists (destdirname ))
{
Directory. createdirectory (destdirname );
}
Foreach (string item in directory. getfiles (sourcedirname ))
{
File. Copy (item, destdirname + path. getfilename (item), true );
}
Foreach (string item in directory. getdirectories (sourcedirname ))
{
Copy (item, destdirname + item. substring (item. lastindexof ("\") + 1 ));
}
}
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.