// Add system reference
Using system. IO;
Private void backup favorites toolstripmenuitem_click (Object sender, eventargs E)
{
String backupfavoritepath;
String systemfavoritepath = getsystemfavoritepath ();
Folderbrowserdialog myfolderbrowserdialog = new folderbrowserdialog ();
Myfolderbrowserdialog. rootfolder = environment. specialfolder. desktop;
If (myfolderbrowserdialog. showdialog () = dialogresult. OK)
{
If (myfolderbrowserdialog. selectedpath! = "")
{
Backupfavoritepath = myfolderbrowserdialog. selectedpath;
Copydir (systemfavoritepath, backupfavoritepath );
}
Else
{
Return;
}
}
}
/// <Summary>
/// Obtain the favorites path from the Registry
/// </Summary>
/// <Returns> </returns>
Private Static string getsystemfavoritepath ()
{
String strsystemfavoritepath = "";
Registrykey HKLM = registry. currentuser;
Registrykey software = HKLM. opensubkey (@ "software/Microsoft/Windows/CurrentVersion/Explorer/Shell Folders", true );
If (software = NULL)
{
Strsystemfavoritepath = "read failed ";
}
Else
{
Strsystemfavoritepath = software. getvalue ("favorites"). tostring ();
}
Return strsystemfavoritepath;
}
/// <Summary>
/// Recursive copy directory file Function
/// </Summary>
/// <Param name = "sourcepath"> </param>
/// <Param name = "targetpath"> </param>
Private void copydir (string sourcepath, string targetpath)
{
Try
{
// Check whether the target directory ends with a directory delimiter. If not, add it.
If (targetpath [targetpath. Length-1]! = System. Io. Path. directoryseparatorchar)
{
Targetpath + = system. Io. Path. directoryseparatorchar;
}
// Determine whether the target directory exists. If it does not exist, create it.
If (! System. Io. Directory. exists (targetpath ))
{
System. Io. Directory. createdirectory (targetpath );
}
// Obtain the file list of the source Directory, which is an array containing the file and directory path
// Use the following method if you direct to the file under the copy target file without including the Directory
// String [] filelist = directory. getfiles (sourcepath );
String [] filelist = system. Io. Directory. getfilesystementries (sourcepath );
// Traverse all files and directories
Foreach (string file in filelist)
{
// Process the file as a directory first. If this directory exists, recursively copy the file under this directory.
If (system. Io. Directory. exists (File ))
{
Copydir (file, targetpath + system. Io. Path. getfilename (File ));
}
// Otherwise, copy the file directly.
Else
{
System. Io. file. Copy (file, targetpath + system. Io. Path. getfilename (file), true );
}
}
}
Catch (exception E)
{
Throw;
}
}