This article introduces several examples. For more information about how to copy, delete, and move C # files and folders in asp.net, see.
The Code is as follows: |
Copy code |
Public class SimpleFileCopy { Static void Main (){ String fileName = "test.txt "; String sourcePath = @ "C: UsersPublicTestFolder "; String targetPath = @ "C: UsersPublicTestFolderSubDir "; String sourceFile = System. IO. Path. Combine (sourcePath, fileName ); String destFile = System. IO. Path. Combine (targetPath, fileName ); If (! System. IO. Directory. Exists (targetPath )){ System. IO. Directory. CreateDirectory (targetPath );} System. IO. File. Copy (sourceFile, destFile, true ); If (System. IO. Directory. Exists (sourcePath )){ String [] files = System. IO. Directory. GetFiles (sourcePath ); Foreach (string s in files) { FileName = System. IO. Path. GetFileName (s ); DestFile = System. IO. Path. Combine (targetPath, fileName ); System. IO. File. Copy (s, destFile, true );} } Else { Console. WriteLine ("Source path does not exist! "); } Console. WriteLine ("Press any key to exit ."); Console. ReadKey ();} } |
The following example shows how to move files and directories.
The Code is as follows: |
Copy code |
Public class SimpleFileMove { Static void Main () { String sourceFile = @ "C: UsersPublicpublictest.txt "; String destinationFile = @ "C: UsersPublicprivatetest.txt "; System. IO. File. Move (sourceFile, destinationFile ); System. IO. Directory. Move (@ "C: UsersPublicpublictest", @ "C: UsersPublicprivate "); }} |
The following example shows how to delete files and directories.
The Code is as follows: |
Copy code |
C # Public class SimpleFileDelete {
Static void Main (){ If (System. IO. File. Exists (@ "C: UsersPublicDeleteTesttest.txt ")) { Try { System. IO. File. Delete (@ "C: UsersPublicDeleteTesttest.txt "); } Catch (System. IO. IOException e) { Console. WriteLine (e. Message); return; } } System. IO. FileInfo fi = new System. IO. FileInfo (@ "C: UsersPublicDeleteTesttest2.txt "); Try {fi. Delete (); } Catch (System. IO. IOException e) { Console. WriteLine (e. Message ); } Try { System. IO. Directory. Delete (@ "C: UsersPublicDeleteTest "); } Catch (System. IO. IOException e) {Console. WriteLine (e. Message ); } If (System. IO. Directory. Exists (@ "C: UsersPublicDeleteTest ")) {Try { System. IO. Directory. Delete (@ "C: UsersPublicDeleteTest", true ); } Catch (System. IO. IOException e ){ Console. WriteLine (e. Message ); } }
System. IO. DirectoryInfo di = new System. IO. DirectoryInfo (@ "C: UsersPublicpublic "); Try { Di. Delete (true ); } Catch (System. IO. IOException e) { Console. WriteLine (e. Message ); } }} |