一个C#实现的目录与文件操作类

发布时间:2020-10-09编辑:脚本学堂
本文介绍下,C#实现的一个目录与文件的操作类,包括产生随机文件名、产生唯一文件名、文件的上传,以及添加文字水印与图片水印的功能等。有需要的朋友,参考下吧。

代码如下:
 

复制代码 代码示例:
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; 
using System.Text; 
using System.Drawing; 
using System.Drawing.Drawing2D; 
using System.Drawing.Imaging; 
     
/// <summary> 
/// 文件操作类 
/// </summary> 
public static class FileCom 

  //普通文件或图片上传 
  #region 文件名命名 和 文件类别验证 
  /// <summary> 
  /// 产生随即文件名 
  /// </summary> 
  /// <returns></returns> 
  public static int GetRandomFileName() 
  { 
  byte[] bytes = new byte[10]; 
  System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider(); 
  rng.GetBytes(bytes); 
  return BitConverter.ToInt32(bytes, 0); 
  } 
  /// <summary> 
  /// 产生随机文件名 
  /// </summary> 
  /// <param name="length">随机文件名长度</param> 
  /// <returns>产生随机文件名</returns> 
  private static string GetRandomFileName(int length) 
  { 
  string ch = "abcdefghijklmnopqrstuvwxyz0123456789"; 
  string strRandomFileName = string.Empty; 
  int intLength = ch.Length; 
  Random rd = new Random(); 
  for (int i = 0; i < length; i++) 
  { 
      strRandomFileName += ch[rd.Next(intLength)]; 
  } 
  return strRandomFileName; 
  } 
  /// <summary> 
  /// 产生唯一文件名 
  /// </summary> 
  /// <param name="strPath">文件夹路径</param> 
  /// <param name="strExt">扩展名</param> 
  /// <returns>文件名</returns> 
  public static string GetOnlyFileName(string strPath, string strExt) 
  { 
  // 若文件夹不存在, 创建文件夹 
  if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(strPath))) 
  { 
      System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(strPath)); 
  } 
  string strTempFileName = string.Empty; 
  string strTempFullName = string.Empty; 
  // 循环方式取唯一文件名 
  while (true) 
  { 
      strTempFileName = GetRandomFileName(15); 
      strTempFullName = strPath + strTempFileName + "." + strExt; 
      if (!System.IO.File.Exists(strTempFullName)) 
      { 
break
      } 
  } 
  return strTempFileName + "." + strExt; 
  } 
  /// <summary> 
  /// 文件名是否图片文件 
  /// </summary> 
  /// <param name="filename">文件名</param> 
  /// <returns>是否图片文件</returns> 
  public static bool IsImageExt(string filename) 
  { 
  if (filename == null || filename == string.Empty) 
      return false; 
  //string[] extArray = { ".gif", ".jpg", ".jpeg", ".bmp", ".png" }; 
  //string[] extArray = {".jpg", ".jpeg"}; 
  string[] extArray = { ".gif", ".jpg", ".jpeg", ".png" }; 
  foreach (string ext in extArray) 
  { 
      if (filename.ToLower().EndsWith(ext)) 
return true; 
  } 
  return false; 
  } 
  /// <summary> 
  /// 文件名是否图片文件或flash文件 
  /// </summary> 
  /// <param name="filename">文件名</param> 
  /// <returns>是否图片文件</returns> 
  public static bool IsImageOrFlashExt(string filename) 
  { 
  if (filename == null || filename == string.Empty) 
      return false; 
  string[] extArray = { ".gif", ".jpg", ".jpeg", ".bmp", ".png", ".swf" }; 
  foreach (string ext in extArray) 
  { 
      if (filename.ToLower().EndsWith(ext)) 
return true; 
  } 
  return false; 
  } 
  #endregion 
  #region 文件夹或文件创建 删除操作/图片 文件上传类 
  /// <summary> 
  /// .net自带IO方法创建文件夹(注意权限问题) 
  /// </summary> 
  /// <param name="folderpath">建立文件夹相对路径</param> 
  /// <returns>true:建立成功 false:此文件夹名已存在</returns> 
  public static void IOCreateFolder(string folderpath) 
  { 
  if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(folderpath))) 
  { 
      System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(folderpath)); 
  } 
  } 
  /// <summary> 
  /// 删除一个文件夹下所有文件和文件夹 
  /// </summary> 
  /// <param name="folderpath"></param> 
  public static void DelFolderandFiles(string folderpath) 
  { 
  if (System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(folderpath))) 
  { 
      System.IO.DirectoryInfo spath = new System.IO.DirectoryInfo(HttpContext.Current.Server.MapPath(folderpath)); 
      foreach (System.IO.DirectoryInfo folder in spath.GetDirectories()) 
      { 
folder.Delete(); 
      } 
      foreach (System.IO.FileInfo file in spath.GetFiles()) 
      { 
file.Delete(); 
      } 
  } 
  } 
  /// <summary> 
  /// 单个文件夹删除类 
  /// </summary> 
  /// <param name="folderpath"></param> 
  public static void DelFolder(string folderpath) 
  { 
  if (System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(folderpath))) 
  { 
      System.IO.Directory.Delete(HttpContext.Current.Server.MapPath(folderpath)); 
  } 
  } 
  /// <summary> 
  /// 单个文件删除类 
  /// </summary> 
  /// <param name="filePath">文件相对路径</param> 
  public static void DelFile(string filePath) 
  { 
  if (System.IO.File.Exists(HttpContext.Current.Server.MapPath(filePath))) 
  { 
      System.IO.File.Delete(HttpContext.Current.Server.MapPath(filePath)); 
  } 
  } 
  /// <summary> 
  /// 普通图片上传类 
  /// </summary> 
  /// <param name="fileName">图片文件名(可返回)</param> 
  /// <param name="file">上传控件名</param> 
  /// <param name="oldpic">原始图片地址</param> 
  /// <param name="filePath">图片存放路径</param> 
  /// <param name="size">图片限制大小的值</param> 
  /// <returns>true:文件上传成功!false:图片类型错误或大小超过限制大小值</returns> 
  public static bool UpLoadImg(ref string fileName, System.Web.UI.WebControls.FileUpload file, string oldpic, string filePath, int size) 
  { 
  fileName = file.PostedFile.FileName; 
  fileName = System.DateTime.Now.ToString("yyMMddhhmmss") + fileName.Substring(fileName.LastIndexOf(".")); 
  string type = fileName.Substring(fileName.LastIndexOf(".") + 1); 
  if (IsImageExt(fileName) && file.PostedFile.ContentLength < size && file.PostedFile.ContentLength > 0) 
  { 
      DelFile(filePath + "//" + oldpic); 
      file.PostedFile.SaveAs(HttpContext.Current.Server.MapPath(filePath + "//" + fileName)); 
      return true; 
  } 
  else 
  { 
      return false; 
  } 
  } 
  /// <summary> 
  /// 普通图片和Flash上传类 
  /// </summary> 
  /// <param name="fileName">图片文件名(可返回)</param> 
  /// <param name="file">上传控件名</param> 
  /// <param name="oldpic">原始图片地址</param> 
  /// <param name="filePath">图片存放路径</param> 
  /// <param name="size">图片限制大小的值</param> 
  /// <returns>true:文件上传成功!false:图片类型错误或大小超过限制大小值</returns> 
  public static bool UpLoadImgAndFlash(ref string fileName, System.Web.UI.WebControls.FileUpload file, string oldpic, string filePath, int size) 
  { 
  fileName = file.PostedFile.FileName; 
  fileName = System.DateTime.Now.ToString("yyMMddhhmmss") + fileName.Substring(fileName.LastIndexOf(".")); 
  string type = fileName.Substring(fileName.LastIndexOf(".") + 1); 
  if (IsImageOrFlashExt(fileName) && file.PostedFile.ContentLength < size && file.PostedFile.ContentLength > 0) 
  { 
      DelFile(filePath + "//" + oldpic); 
      file.PostedFile.SaveAs(HttpContext.Current.Server.MapPath(filePath + "//" + fileName)); 
      return true; 
  } 
  else 
  { 
      return false; 
  } 
  } 
  /// <summary> 
  /// 检测文件真实类型 
  /// </summary> 
  /// <param name="hifile">FileUpload控件对象</param> 
  /// <returns>是否是相关文件类型</returns> 
  /*文件扩展名说明
   *7173        gif 
   *255216      jpg
   *13780       png
   *6677        bmp
   *239187      txt,aspx,asp,sql
   *208207      xls.doc.ppt
   *6063        xml
   *6033        htm,html
   *4742        js
   *8075        xlsx,zip,pptx,mmap,zip
   *8297        rar   
   *01accdb,mdb
   *7790        exe,dll 
   *5666        psd 
   *255254      rdp 
   *10056       bt种子 
   *64101       bat 
   */ 
  private static bool IsAllowedExtension(HttpPostedFile hifile) 
  { 
  bool ret = false; 
  System.IO.FileStream fs = new System.IO.FileStream(hifile.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); 
  System.IO.BinaryReader r = new System.IO.BinaryReader(fs); 
  string fileclass = ""; 
  byte buffer; 
  try 
  { 
      buffer = r.ReadByte(); 
      fileclass = buffer.ToString(); 
      buffer = r.ReadByte(); 
      fileclass += buffer.ToString(); 
  } 
  catch 
  { 
      return false; 
  } 
  r.Close(); 
  fs.Close(); 
  String[] fileType = { "255216", "7173", "6677", "13780", "8297", "5549", "870", "87111", "8075" }; 
  for (int i = 0; i < fileType.Length; i++) 
  { 
      if (fileclass == fileType[i]) 
      { 
ret = true; 
break; 
      } 
  } 
  return ret; 
  } 
  /// <summary> 
  /// 任意文件上传类 
  /// </summary> 
  /// <param name="fileName">图片文件名(可返回)</param> 
  /// <param name="file">上传控件名</param> 
  /// <param name="oldfile">原始文件名</param> 
  /// <param name="filePath">存放路径</param> 
  public static void UpLoadFile(ref string fileName, System.Web.UI.WebControls.FileUpload file, string oldfile, string filePath) 
  { 
  fileName = file.PostedFile.FileName; 
  fileName = System.DateTime.Now.ToString("yyMMddhhmmss") + fileName.Substring(fileName.LastIndexOf(".")); 
  DelFile(filePath + "//" + oldfile); 
  file.PostedFile.SaveAs(HttpContext.Current.Server.MapPath(filePath + "//" + fileName)); 
  } 
  #endregion 
  //#region 验证上传附件扩展名 
  ///// <summary> 
  ///// 验证上传附件扩展名 
  ///// </summary>  www.jb200.com
  ///// <param name="file">FileUpload控件</param> 
  ///// <returns>true表示允许,false不允许</returns> 
  //public static bool ValidExt(System.Web.UI.WebControls.FileUpload file) 
  //{ 
  //    BLL.m_config bconfig = new BLL.m_config(); 
  //    Model.m_config mconfig = bconfig.GetModel("ValidExt"); 
  //    string[] strValiddExt = mconfig.config_value.Split('|'); 
  //    bool flag = false; 
  //    foreach (string ext in strValiddExt) 
  //    { 
  //        if (ext == file.FileName.Substring(file.FileName.LastIndexOf('.') + 1).ToLower()) 
  //  flag = true; 
  //    } 
  //    return flag; 
  //} 
  //#endregion 
  /// <summary> 
  /// 会产生graphics异常的PixelFormat 
  /// </summary> 
  private static PixelFormat[] indexedPixelFormats = { PixelFormat.Undefined, PixelFormat.DontCare, 
    PixelFormat.Format16bppArgb1555, PixelFormat.Format1bppIndexed, PixelFormat.Format4bppIndexed, 
    PixelFormat.Format8bppIndexed 
        }; 
  /// <summary> 
  /// 判断图片的PixelFormat 是否在 引发异常的 PixelFormat 之中 
  /// </summary> 
  /// <param name="imgPixelFormat">原图片的PixelFormat</param> 
  /// <returns></returns> 
  private static bool IsPixelFormatIndexed(PixelFormat imgPixelFormat) 
  { 
  foreach (PixelFormat pf in indexedPixelFormats) 
  { 
      if (pf.Equals(imgPixelFormat)) return true; 
  } 
  return false; 
  } 
  /// <summary> 
  /// 添加图片水印 
  /// </summary> 
  /// <param name="CmyID">企业ID</param> 
  /// <param name="UpLoadPath">原始图片路径</param> 
  public static string AddWaterMark(string filename, int CmyID, string UpLoadPath) 
  { 
  string newfilename = string.Empty; 
  SanRencms.BLL.WaterMarkConfig bwmc = new SanRenCMS.BLL.WaterMarkConfig(); 
  SanRenCMS.Model.WaterMarkConfig mwmc = bwmc.GetModel("CmyID=" + CmyID.ToString()); 
  switch (mwmc.WaterMarkType) 
  { 
      case 1: 
newfilename = LetterWaterMark(filename, mwmc, UpLoadPath); 
break; 
      case 2: 
newfilename = PicWaterMark(filename, mwmc, UpLoadPath); 
break; 
  } 
  return newfilename; 
  } 
  /// <summary> 
  /// 图片水印上传 
  /// </summary> 
  /// <param name="FilePicName">上传控件</param> 
  /// <param name="FilePicPath"></param> 
  /// <param name="UpLoadPicPath"></param> 
  /// <returns></returns> 
  public static string PicWaterMark(string filename, SanRenCMS.Model.WaterMarkConfig mwmc, string UpLoadPicPath) 
  { 
  string newfilename = string.Empty; 
  string MarkHWStr = mwmc.WaterMarkSize; //"50|186";//图片水印的高宽 
  string[] MyWaterMarkHW = MarkHWStr.Split(new char[] { '|' }); 
  string WaterMarkPath = HttpContext.Current.Server.MapPath(mwmc.WaterMarkPhoto); 
  string PicPath = HttpContext.Current.Server.MapPath(UpLoadPicPath) + "//" + filename; 
  newfilename = Guid.NewGuid().ToString() + ".jpg"; 
  string NewPicPath = HttpContext.Current.Server.MapPath(UpLoadPicPath) + "//" + newfilename; 
  int WaterMarkH = int.Parse(MyWaterMarkHW[0]); 
  int WaterMarkW = int.Parse(MyWaterMarkHW[1]); 
  int WaterMarkLight = 80;// 50;//透明度 
  int WaterMarkPos = mwmc.WaterMarkPosition; //3;//水印图位置(1左上,2右上,3右下,4左下) 
     
  System.Drawing.Image image = System.Drawing.Image.FromFile(PicPath); 
  System.Drawing.Image copyImage = System.Drawing.Image.FromFile(WaterMarkPath); 
  float[][] numArray2 = new float[5][]; 
  float[] numArray3 = new float[5]; 
  numArray3[0] = 1f;  //www.jb200.com
  numArray2[0] = numArray3; 
  float[] numArray4 = new float[5]; 
  numArray4[1] = 1f; 
  numArray2[1] = numArray4; 
  float[] numArray5 = new float[5]; 
  numArray5[2] = 1f; 
  numArray2[2] = numArray5; 
  float[] numArray6 = new float[5]; 
  numArray6[3] = ((float)WaterMarkLight) / 100f; 
  numArray2[3] = numArray6; 
  float[] numArray7 = new float[5]; 
  numArray7[4] = 1f; 
  numArray2[4] = numArray7; 
  float[][] newColorMatrix = numArray2; 
  ColorMatrix matrix = new ColorMatrix(newColorMatrix); 
  ImageAttributes imageAttr = new ImageAttributes(); 
  imageAttr.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); 
  Graphics g = null; 
  if (IsPixelFormatIndexed(image.PixelFormat)) 
  { 
      Bitmap bmp = new Bitmap(image.Width, image.Height, PixelFormat.Format32bppArgb); 
      g = Graphics.FromImage(image); 
  } 
  else 
      g = Graphics.FromImage(image); 
  switch (WaterMarkPos) 
  { 
      case 1: 
g.DrawImage(copyImage, new Rectangle(0, 0, WaterMarkW, WaterMarkH), 0, 0, WaterMarkW, WaterMarkH, GraphicsUnit.Pixel, imageAttr); 
break; 
      case 2: 
g.DrawImage(copyImage, new Rectangle(0, image.Height - WaterMarkH, WaterMarkW, WaterMarkH), 0, 0, WaterMarkW, WaterMarkH, GraphicsUnit.Pixel, imageAttr); 
break; 
      case 3: 
g.DrawImage(copyImage, new Rectangle(image.Width - WaterMarkW, 0, WaterMarkW, WaterMarkH), 0, 0, WaterMarkW, WaterMarkH, GraphicsUnit.Pixel, imageAttr); 
break; 
      case 4: 
g.DrawImage(copyImage, new Rectangle(image.Width - WaterMarkW, image.Height - WaterMarkH, WaterMarkW, WaterMarkH), 0, 0, WaterMarkW, WaterMarkH, GraphicsUnit.Pixel, imageAttr); 
break; 
      case 5: 
g.DrawImage(copyImage, new Rectangle((image.Width - WaterMarkW) / 2, (image.Height - WaterMarkH) / 2, WaterMarkW, WaterMarkH), 0, 0, WaterMarkW, WaterMarkH, GraphicsUnit.Pixel, imageAttr); 
break; 
  } 
  g.Dispose(); 
  image.Save(NewPicPath); 
  image.Dispose(); 
  if (File.Exists(PicPath)) 
  { 
      File.Delete(PicPath); 
  } 
  return newfilename; 
  } 
  /// <summary> 
  /// 添加字体水印 
  /// </summary> 
  /// <param name="CmyID">企业ID</param> 
  /// <param name="UpLoadPicPath">要加水印图片的路径</param> 
  /// <returns></returns> 
  public static string LetterWaterMark(string filename, SanRenCMS.Model.WaterMarkConfig mwmc, string UpLoadPicPath) 
  { 
  string newfilename = string.Empty; 
  Font f; 
  string PicPath = HttpContext.Current.Server.MapPath(UpLoadPicPath) + "//" + filename; 
  //HttpContext.Current.Response.Write(filename); 
  newfilename = Guid.NewGuid().ToString() + ".jpg"; 
  //DateTime.Now.ToString("yyMMddhhmmss") + ".jpg"; 
  string NewPicPath = HttpContext.Current.Server.MapPath(UpLoadPicPath) + "//" + newfilename; 
  //HttpContext.Current.Response.Write(NewPicPath); 
  string WaterMarkStr = mwmc.WaterMarkWord;//水印文字 
  int WaterMarkFontSize = mwmc.WaterMarkWorkSize; //文字大小,单位PX 
  string WaterMarkFontName = mwmc.WaterMarkFont;// "华文细黑";//字体 
  string WaterMarkFontColor = mwmc.WaterMarkWordColor;// "009999";//字体颜色 
  bool WaterMarkIsBold = mwmc.isStrong == 1 ? true : false;//是否加粗 
  int WaterMarkPos = mwmc.WaterMarkPosition;//水印位置 
  System.Drawing.Image image = System.Drawing.Image.FromFile(PicPath); 
  Graphics g = null; 
  if (IsPixelFormatIndexed(image.PixelFormat)) 
  { 
      Bitmap bmp = new Bitmap(image.Width, image.Height, PixelFormat.Format32bppArgb); 
      g = Graphics.FromImage(image); 
  } 
  else 
      g = Graphics.FromImage(image); 
  g.CompositingQuality = CompositingQuality.HighQuality; 
  g.SmoothingMode = SmoothingMode.HighQuality; 
  g.InterpolationMode = InterpolationMode.HighQualityBicubic; 
  g.DrawImage(image, 0, 0, image.Width, image.Height); 
  if (WaterMarkIsBold) 
  { 
      f = new Font(WaterMarkFontName, (float)WaterMarkFontSize, FontStyle.Bold); 
  } 
  else 
  { 
      f = new Font(WaterMarkFontName, (float)WaterMarkFontSize); 
  } 
  Brush b = new SolidBrush(ColorTranslator.FromHtml("#" + WaterMarkFontColor)); 
  string addText = WaterMarkStr; 
  //switch (WaterMarkPos) 
  //{ 
  //    case 1: 
  //        g.DrawString(addText, f, b, (float)0f, (float)0f); 
  //        break; 
  //    case 2: 
  //        g.DrawString(addText, f, b, (float)0f, (float)0f); 
  //        break; 
  //    case 3: 
  //        g.DrawImage(copyImage, new Rectangle(image.Width - WaterMarkW, image.Height - WaterMarkH, WaterMarkW, WaterMarkH), 0, 0, WaterMarkW, WaterMarkH, GraphicsUnit.Pixel, imageAttr); 
  //        break; 
  //    case 4: 
  //        g.DrawImage(copyImage, new Rectangle(0, image.Height - WaterMarkH, WaterMarkW, WaterMarkH), 0, 0, WaterMarkW, WaterMarkH, GraphicsUnit.Pixel, imageAttr); 
  //        break; 
  //} 
  g.DrawString(addText, f, b, (float)(image.Width / 2), (float)(image.Height / 2)); 
  //g.DrawString(addText,f,b, 
  g.Dispose(); 
  try 
  { 
      //HttpContext.Current.Response.Write(NewPicPath); 
      image.Save(NewPicPath, ImageFormat.Jpeg); 
  } 
  catch (Exception exx) 
  { 
      HttpContext.Current.Response.Write(exx.ToString()); 
  } 
  finally 
  { 
      image.Dispose(); 
  } 
  if (File.Exists(PicPath)) 
  { 
      File.Delete(PicPath); 
  } 
  return newfilename; 
 }