asp.net中C#文件和文件夹的复制、删除、移动实现程序

作者:袖梨 2022-06-25
 代码如下 复制代码

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();      } 
}     

下面的示例演示如何移动文件和目录。

 代码如下 复制代码

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");    
 }  }     

下面的示例演示如何删除文件和目录。

 代码如下 复制代码


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);
 }
 }} 

相关文章

精彩推荐