.net中常需对文件夹以及常用的操作方法

譬如说,用户注册时,创立一个文件夹;删除用户时,删除相应的文件夹;移动文件夹……
积累了一些方法,记于此:
 /// <sumary>
/// 文件夹大小
/// </sumary>
  public static long spacesize(string path2)
  {
            string personalname=path2;

   //System.Web.UI.Page pg=new Page();
      //personalname=pg.Server.MapPath(pg.Request.ApplicationPath)+"\\"+path2;

   long size=0;
   string path=personalname;
   string erromsg="";
   DirectoryInfo d=new DirectoryInfo(path);
   try
   {
    FileInfo []fis=d.GetFiles();
    foreach(FileInfo fi in fis)
    {       
     size+=fi.Length;
    }       
   }
   catch(Exception ex)
   {       
     erromsg=ex.Message;    
      
   } 
   path=personalname+"\\image";
      
   d=new DirectoryInfo(path);
   try
   {
    FileInfo []fis=d.GetFiles();
    foreach(FileInfo fi in fis)
    {        
     size+=fi.Length;
    }
          
   }
   catch(Exception ex)
   {           
    erromsg+=ex.Message;         
   }
   size=size/1048576;//Byte转换成M Byte
   return size;    
          
  }   
  
/// 创建文件夹
///
  public static bool creatofilecase(string filecasename)
  {
      bool success=false;
            System.IO.Directory.CreateDirectory(filecasename);   
   if(System.IO.Directory.Exists(filecasename))
    success=true;
   
     return success;
  }
  //册除文件夹
  public static bool delfilecase(string filecasename)
  {
   bool success=false;
   System.IO.Directory.Delete(filecasename);
   if(!System.IO.Directory.Exists(filecasename))
    success=true;      
   return success;
  
  }
  //移动文件夹
  public static bool movefilecase(string filecasename,string objfilecase)
  {
   bool success=false;
   System.IO.Directory.Move(filecasename,objfilecase);
   if(System.IO.Directory.Exists(objfilecase))
    success=true;
   return success; 
   
  }
  ///查看目录大小
 public static long DirSize(DirectoryInfo d)
 {   
  long Size = 0;   
  // Add file sizes.
  FileInfo[] fis = d.GetFiles();
  foreach (FileInfo fi in fis)
  {     
   Size += fi.Length;   
  }
  // Add subdirectory sizes.
  DirectoryInfo[] dis = d.GetDirectories();
  foreach (DirectoryInfo di in dis)
  {
  Size += DirSize(di);  
  }
  return(Size); 
   }

  
  ///拷贝文件,建立用户个人默认页面
  ///
  public static bool copyfile(string creatfile,string desfilename)
  {
   bool success=false;         
      File.Copy(creatfile,desfilename,true);
      if(File.Exists(desfilename))
      success=true;
   return success;    
  }

  //移动文件
  public static bool movefile(string sourcefile,string objfile)
  {
   bool success=false;     
   File.Move(sourcefile,objfile);
   if(!File.Exists(sourcefile))
    success=true;
   return success;  
  
  }
  //文件是否存在
  public static bool havefile(string path)
  {
   bool success=false; 
   if(!File.Exists(path))
    success=true;
   return success;  
  
  }
  //删除文件
  public static bool delfile(string path)
  {    
   bool success=false;       
      File.Delete(path);
   if(!File.Exists(path))
    success=true;
   return success;  
  }

你可能感兴趣的:(.net)