常用类

1. c#发起http调用WCF接口帮助类

  public static string SendHttpRequest(string requestURI, string requestMethod, string json)
     {
         //json格式请求数据
         string requestData = json;
         //拼接URL
         string serviceUrl = string.Format("{0}/{1}", requestURI, requestMethod);
         HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
         //utf-8编码
         byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(requestData);

         //post请求 
         myRequest.Method = "POST";
         myRequest.ContentLength = buf.Length;
         //指定为json否则会出错
         myRequest.Accept = "application/json";
         myRequest.ContentType = "application/json";
         //myRequest.ContentType = "text/json";
         myRequest.MaximumAutomaticRedirections = 1;
         myRequest.AllowAutoRedirect = true;

         Stream newStream = myRequest.GetRequestStream();
         newStream.Write(buf, 0, buf.Length);
         newStream.Close();

         //获得接口返回值,格式为: {"VerifyResult":"aksjdfkasdf"} 
         HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
         StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
         string ReqResult = reader.ReadToEnd();
         reader.Close();
         myResponse.Close();
         return ReqResult;
     }

2. 缓存帮助类

 public class Cache    
    {

        //也可以用下面这句代码代替上面这句代码  
      private static System.Web.Caching.Cache _cache = HttpRuntime.Cache;
        /// <summary>  
        /// 设置数据缓存  
        /// </summary>  
        /// <param name="key"></param>  
        /// <param name="val"></param>  
        /// <returns></returns>  
        public static object SetCache(string key, object val)
        {
            if (_cache[key] == null)
                _cache.Insert(key, val, null, DateTime.Now.AddDays(1), TimeSpan.Zero);
            return _cache[key];
        }
        /// <summary>  
        /// 设置数据缓存  
        /// </summary>  
        /// <param name="key"></param>  
        /// <param name="val"></param>  
        /// <param name="minute">缓存的时间长度(单位:分钟)</param>  
        /// <returns></returns>  
        public static object SetCache(string key, object val, double minute)
        {
            if (_cache[key] == null)
                _cache.Insert(key, val, null, DateTime.Now.AddMinutes(minute), TimeSpan.Zero);
            return _cache[key];
        }
        /// <summary>  
        ///  获取数据缓存  
        /// </summary>  
        /// <param name="key"></param>  
        /// <returns></returns>  
        public static object GetCache(string key)
        {
            return _cache[key];
        }
        /// <summary>  
        /// 移除指定数据缓存  
        /// </summary>  
        /// <param name="key">要移除缓存的键</param>  
        public static void RemoveCache(string key)
        {
            if (_cache[key] != null)
                _cache.Remove(key);
        }
        /// <summary>  
        /// 移除全部缓存  
        /// </summary>  
        public static void RemoveAllCache()
        {
            //_cache.GetEnumerator()方法是检索用于循环访问包含在缓存中的键设置及其值的字典枚举数。  
            IDictionaryEnumerator _cacheEnum = _cache.GetEnumerator();
            // MoveNext()方法是将枚举数推进到集合的下一个元素。  
            while (_cacheEnum.MoveNext())
            {
                _cache.Remove(_cacheEnum.Key.ToString());
            }
        }  

    }

3.上传图片

   public static ResultPic UploadFile(HttpPostedFileBase basce) {

          ResultPic res = new ResultPic();
          res.avatarUrls = new ArrayList();
          res.msg = "false";
          res.success = false;
          res.sourceUrl = "";
          string virtualPath = "";
          if (basce != null)
          {
              //获取随机数
              string code = DateTime.Now.ToString("yyyyMMdd") + CreateBum.Instance().CreateRandomCode(8);
              int avatarNumber = 1;
              //获取图片保存地址
              var url = "http://" + HttpContext.Current.Request.Url.Authority;

              string uploadpath = ConfigurationManager.AppSettings["UploadPath"].ToString();
              if (!Directory.Exists(HttpContext.Current.Server.MapPath(uploadpath)))
                  Directory.CreateDirectory(uploadpath);

              try
              {

                  string exting = Path.GetExtension(basce.FileName);

                  virtualPath = uploadpath + code + avatarNumber + exting;
                  //string virtualPath = string.Format("/upload/csharp_avatar{0}_{1}.jpg", avatarNumber, fileName);
                  res.avatarUrls.Add(url + virtualPath);
                  res.sourceUrl = url + virtualPath;
                  basce.SaveAs(HttpContext.Current.Server.MapPath(virtualPath));
                  res.success = true;
                  res.replationUrl = virtualPath;
                  res.msg = "上传成功";

              }
              catch (Exception ex)
              {

                  throw ex;
              }




          }

          return res;

      }

  public static ResultPic UploadFile(HttpPostedFileBase basce) {

          ResultPic res = new ResultPic();
          res.avatarUrls = new ArrayList();
          res.msg = "false";
          res.success = false;
          res.sourceUrl = "";
          string virtualPath = "";
          if (basce != null)
          {
              //获取随机数
              string code = DateTime.Now.ToString("yyyyMMdd") + CreateBum.Instance().CreateRandomCode(8);
              int avatarNumber = 1;
              //获取图片保存地址
              var url = "http://" + HttpContext.Current.Request.Url.Authority;

              string uploadpath = ConfigurationManager.AppSettings["UploadPath"].ToString();
              if (!Directory.Exists(HttpContext.Current.Server.MapPath(uploadpath)))
                  Directory.CreateDirectory(uploadpath);

              try
              {

                  string exting = Path.GetExtension(basce.FileName);

                  virtualPath = uploadpath + code + avatarNumber + exting;
                  //string virtualPath = string.Format("/upload/csharp_avatar{0}_{1}.jpg", avatarNumber, fileName);
                  res.avatarUrls.Add(url + virtualPath);
                  res.sourceUrl = url + virtualPath;
                  basce.SaveAs(HttpContext.Current.Server.MapPath(virtualPath));
                  res.success = true;
                  res.replationUrl = virtualPath;
                  res.msg = "上传成功";

              }
              catch (Exception ex)
              {

                  throw ex;
              }




          }

          return res;

      }



//生成随机数
    public string CreateRandomCode(int length)
        {
            string[] codes = new string[36] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
            StringBuilder randomCode = new StringBuilder();
            Random rand = new Random();
            for (int i = 0; i < length; i++)
            {
                randomCode.Append(codes[rand.Next(codes.Length)]);
            }
            return randomCode.ToString();
        }


4.文件操作相关类

using System;
using System.Diagnostics;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using Microsoft.Win32;

namespace Lzd.Mvc.Common
{
    /// <summary>
    /// 文件操作工具类
    /// </summary>
    [Serializable]
    public class FileUtil : IDisposable
    {
        private bool _alreadyDispose = false;
        #region 构造函数
        public FileUtil()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }
        ~FileUtil()
        {
            Dispose();
        }
        protected virtual void Dispose(bool isDisposing)
        {
            if (_alreadyDispose) return;
            //if (isDisposing)
            //{
            //     if (xml != null)
            //     {
            //         xml = null;
            //     }
            //}
            _alreadyDispose = true;
        }
        #endregion

        #region IDisposable 成员

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion

        #region 取得文件文件名、后缀名、大小
        /// <summary>
        /// 获取文件名(包含扩展名)
        /// </summary>
        /// <param name="FileFullPath">文件全路径</param>
        /// <returns>string</returns>
        public string GetFileName(string FileFullPath)
        {
            if (File.Exists(FileFullPath) == true)
            {
                FileInfo F = new FileInfo(FileFullPath);  //FileInfo类为提供创建、复制、删除等方法
                return F.Name;  //获取文件名(包含扩展名)
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 获取文件名(可包含扩展名)
        /// </summary>
        /// <param name="FileFullPath">文件全路径</param>
        /// <param name="IncludeExtension">是否包含扩展名</param>
        /// <returns>string</returns>
        public string GetFileName(string FileFullPath, bool IncludeExtension)
        {
            if (File.Exists(FileFullPath) == true)
            {
                FileInfo F = new FileInfo(FileFullPath);
                if (IncludeExtension == true)
                {
                    return F.Name;   //返回文件名(包含扩展名)
                }
                else
                {
                    return F.Name.Replace(F.Extension, "");  //把扩展名替换为空字符
                }
            }
            else
            {
                return null;
            }
        }

        /****************************************
          * 函数名称:GetPostfixStr
          * 功能说明:取得文件后缀名
          * 参     数:filename:文件名称
          * 调用示列:
          *            string filename = "aaa.aspx";        
          *            string s = FileUtil.GetPostfixStr(filename);         
         *****************************************/
        /// <summary>
        /// 取后缀名
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <returns>.gif|.html格式</returns>
        public static string GetPostfixStr(string filename)
        {
            int start = filename.LastIndexOf(".");
            int length = filename.Length;
            string postfix = filename.Substring(start, length - start);
            return postfix;
        }
        /// <summary>
        /// 获取文件扩展名
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string GetFileExtension(string fileName)
        {
            string extension = null;
            if (fileName != String.Empty && fileName.IndexOf('.') != -1)
            {
                int start = 0, step = 0;
                start = fileName.LastIndexOf('.') + 1;
                step = fileName.Length - start;
                extension = fileName.Substring(start, step);
            }
            return extension;
        }
        /// <summary>
        /// 由文件全路径获取文件扩展名
        /// </summary>
        /// <param name="FileFullPath">文件全路径</param>
        /// <returns>string</returns>
        public static string GetPathFileExtension(string FileFullPath)
        {
            if (File.Exists(FileFullPath) == true)
            {
                FileInfo F = new FileInfo(FileFullPath);
                return F.Extension;  //获取文件扩展名(包含".",如:".mp3")

            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 获取文件大小
        /// </summary>
        /// <param name="FileFullPath">文件全路径</param>
        /// <returns>string</returns>
        public static string GetFileSize(string FileFullPath)
        {
            if (File.Exists(FileFullPath) == true)
            {
                FileInfo F = new FileInfo(FileFullPath);
                long FL = F.Length;
                if (FL > (1024 * 1024 * 1024))  //由大向小来判断文件的大小
                {
                    return Math.Round((FL + 0.00) / (1024 * 1024 * 1024), 2).ToString() + " GB";  //将双精度浮点数舍入到指定的小数(long类型与double类型运算,结果会是一个double类型)
                }
                else if (FL > (1024 * 1024))
                {
                    return Math.Round((FL + 0.00) / (1024 * 1024), 2).ToString() + " MB";
                }
                else if (FL > 1024)
                {
                    return Math.Round((FL + 0.00) / 1024, 2).ToString() + " KB";
                }
                else
                {
                    return FL.ToString();
                }
            }
            else
            {
                return null;
            }
        }

        #endregion

          #region 写文件
        /****************************************
          * 函数名称:WriteFile
          * 功能说明:写文件,会覆盖掉以前的内容
          * 参     数:Path:文件路径,Strings:文本内容
          * 调用示列:
          *            string Path = Server.MapPath("Default2.aspx");       
          *            string Strings = "这是我写的内容啊";
          *            FileUtil.WriteFile(Path,Strings);
         *****************************************/
        /// <summary>
        /// 写文件
        /// </summary>
        /// <param name="Path">文件路径</param>
        /// <param name="Strings">文件内容</param>
        public static void WriteFile(string Path, string Strings)
        {
            if (!System.IO.File.Exists(Path))
            {
                System.IO.FileStream f = System.IO.File.Create(Path);
                f.Close();
            }
            System.IO.StreamWriter f2 = new System.IO.StreamWriter(Path, false, System.Text.Encoding.GetEncoding("gb2312"));
            f2.Write(Strings);
            f2.Close();
            f2.Dispose();
        }
        #endregion

        #region 读文件
        /****************************************
          * 函数名称:ReadFile
          * 功能说明:读取文本内容
          * 参     数:Path:文件路径
          * 调用示列:
          *            string Path = Server.MapPath("Default2.aspx");       
          *            string s = FileUtil.ReadFile(Path);
         *****************************************/
        /// <summary>
        /// 读文件
        /// </summary>
        /// <param name="Path">文件路径</param>
        /// <returns></returns>
        public static string ReadFile(string Path)
        {
            string s = "";
            if (!System.IO.File.Exists(Path))
                s = "不存在相应的目录";
            else
            {
                StreamReader f2 = new StreamReader(Path, System.Text.Encoding.GetEncoding("gb2312"));
                s = f2.ReadToEnd();
                f2.Close();
                f2.Dispose();
            }

            return s;
        }
        /// <summary>
        /// 根据传来的文件全路径,外部打开文件,默认用系统注册类型关联软件打开
        /// </summary>
        /// <param name="FileFullPath">文件的全路径</param>
        /// <returns>bool</returns>
        public static bool OpenFile(string FileFullPath)
        {
            if (File.Exists(FileFullPath) == true)
            {
                System.Diagnostics.Process.Start(FileFullPath);  //打开文件,默认用系统注册类型关联软件打开
                return true;
            }
            else
            {
                return false;
            }
        }

        #endregion
  #region 追加文件
        /****************************************
          * 函数名称:FileAdd
          * 功能说明:追加文件内容
          * 参     数:Path:文件路径,strings:内容
          * 调用示列:
          *            string Path = Server.MapPath("Default2.aspx");     
          *            string Strings = "新追加内容";
          *            FileUtil.FileAdd(Path, Strings);
         *****************************************/
        /// <summary>
        /// 追加文件
        /// </summary>
        /// <param name="Path">文件路径</param>
        /// <param name="strings">内容</param>
        public static void FileAdd(string Path, string strings)
        {
            StreamWriter sw = File.AppendText(Path);
            sw.Write(strings);
            sw.Flush();
            sw.Close();
        }

        /// <summary>
        /// 向文本追加字符
        /// </summary>
        /// <param name="fileFullPath">全路径</param>
        /// <param name="str">追加字符</param>
        public static void appendStrToTxtFile(string fileFullPath, string str)
        {
            String errPath = fileFullPath;
            FileStream errStr = null;//文件流
            StreamWriter errWri = null;//写入流
            try
            {
                if (File.Exists(errPath))//判断文件是否存在   
                {
                    errStr = new FileStream(errPath, FileMode.Append);//打开文件搜寻到文件尾   
                }
                else
                {
                    errStr = new FileStream(errPath, FileMode.Create);//创建文件   
                }
                errWri = new StreamWriter(errStr, System.Text.Encoding.UTF8);//new写入流指定编码  
                errWri.Write(str);//写入文件
            }
            catch (UnauthorizedAccessException err)
            {
                throw err;
            }
            catch (IOException err)
            {
                throw err;
            }
            finally
            {
                if (errWri != null)
                {
                    errWri.Close();
                }
                if (errStr != null)
                {
                    errStr.Close();
                }
            }
        }
        #endregion

        #region 拷贝、转换文件
        /****************************************
          * 函数名称:FileCoppy
          * 功能说明:拷贝文件
          * 参     数:OrignFile:原始文件,NewFile:新文件路径
          * 调用示列:
          *            string orignFile = Server.MapPath("Default2.aspx");     
          *            string NewFile = Server.MapPath("Default3.aspx");
          *            FileUtil.FileCoppy(OrignFile, NewFile);
         *****************************************/
        /// <summary>
        /// 拷贝文件
        /// </summary>
        /// <param name="OrignFile">原始文件</param>
        /// <param name="NewFile">新文件路径</param>
        public static void FileCoppy(string orignFile, string NewFile)
        {
            File.Copy(orignFile, NewFile, true);
        }
        /// <summary>
        /// 文件转换成二进制,返回二进制数组Byte[]
        /// </summary>
        /// <param name="FileFullPath">文件全路径</param>
        /// <returns>byte[] 包含文件流的二进制数组</returns>
        public static byte[] FileToStreamByte(string FileFullPath)
        {
            if (File.Exists(FileFullPath) == true)
            {
                FileStream FS = new FileStream(FileFullPath, FileMode.Open); //创建一个文件流
                byte[] fileData = new byte[FS.Length];                       //创建一个字节数组,用于保存流
                FS.Read(fileData, 0, fileData.Length);                       //从流中读取字节块,保存到缓存中
                FS.Close();                                                  //关闭流(一定得关闭,否则流一直存在)
                return fileData;                                             //返回字节数组
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 二进制数组Byte[]生成文件
        /// </summary>
        /// <param name="FileFullPath">要生成的文件全路径</param>
        /// <param name="StreamByte">要生成文件的二进制 Byte 数组</param>
        /// <returns>bool 是否生成成功</returns>
        public static bool ByteStreamToFile(string FileFullPath, byte[] StreamByte)
        {
            try
            {
                if (File.Exists(FileFullPath) == true)  //判断要创建的文件是否存在,若存在则先删除
                {
                    File.Delete(FileFullPath);
                }
                FileStream FS = new FileStream(FileFullPath, FileMode.OpenOrCreate);  //创建文件流(打开或创建的方式)
                FS.Write(StreamByte, 0, StreamByte.Length);  //把文件流写到文件中
                FS.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }

        #endregion

        #region 删除文件
        /****************************************
          * 函数名称:FileDel
          * 功能说明:删除文件
          * 参     数:Path:文件路径
          * 调用示列:
          *            string Path = Server.MapPath("Default3.aspx");    
          *            FileUtil.FileDel(Path);
         *****************************************/
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="Path">路径</param>
        public static void FileDel(string Path)
        {
            File.Delete(Path);
        }
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="FileFullPath">文件的全路径.</param>
        /// <returns>bool</returns>
        public static bool DeleteFile(string FileFullPath)
        {
            if (File.Exists(FileFullPath) == true) //用静态类判断文件是否存在
            {
                File.SetAttributes(FileFullPath, FileAttributes.Normal); //设置文件的属性为正常(如果文件为只读的话直接删除会报错)
                File.Delete(FileFullPath); //删除文件
                return true;
            }
            else  //文件不存在
            {
                return false;
            }
        }
        #endregion

        #region 移动文件
        /****************************************
          * 函数名称:FileMove
          * 功能说明:移动文件
          * 参     数:OrignFile:原始路径,NewFile:新文件路径
          * 调用示列:
          *             string orignFile = Server.MapPath("../说明.txt");    
          *             string NewFile = Server.MapPath("http://www.cnblogs.com/说明.txt");
          *             FileUtil.FileMove(OrignFile, NewFile);
         *****************************************/
        /// <summary>
        /// 移动文件
        /// </summary>
        /// <param name="OrignFile">原始路径</param>
        /// <param name="NewFile">新路径</param>
        public static void FileMove(string orignFile, string NewFile)
        {
            File.Move(orignFile, NewFile);
        }
        #endregion

        #region 在当前目录下创建目录
        /****************************************
          * 函数名称:FolderCreate
          * 功能说明:在当前目录下创建目录
          * 参     数:OrignFolder:当前目录,NewFloder:新目录
          * 调用示列:
          *            string orignFolder = Server.MapPath("test/");    
          *            string NewFloder = "new";
          *            FileUtil.FolderCreate(OrignFolder, NewFloder); 
         *****************************************/
        /// <summary>
        /// 在当前目录下创建目录
        /// </summary>
        /// <param name="OrignFolder">当前目录</param>
        /// <param name="NewFloder">新目录</param>
        public static void FolderCreate(string orignFolder, string NewFloder)
        {
            Directory.SetCurrentDirectory(orignFolder);
            Directory.CreateDirectory(NewFloder);
        }
        #endregion
           #region 递归删除文件夹目录及文件
        /****************************************
          * 函数名称:DeleteFolder
          * 功能说明:递归删除文件夹目录及文件
          * 参     数:dir:文件夹路径
          * 调用示列:
          *            string dir = Server.MapPath("test/");  
          *            FileUtil.DeleteFolder(dir);       
         *****************************************/
        /// <summary>
        /// 递归删除文件夹目录及文件
        /// </summary>
        /// <param name="dir"></param>
        /// <returns></returns>
        public static void DeleteFolder(string dir)
        {
            if (Directory.Exists(dir)) //如果存在这个文件夹删除之 
            {
                foreach (string d in Directory.GetFileSystemEntries(dir))
                {
                    if (File.Exists(d))
                        File.Delete(d); //直接删除其中的文件 
                    else
                        DeleteFolder(d); //递归删除子文件夹 
                }
                Directory.Delete(dir); //删除已空文件夹 
            }

        }

        #endregion
          #region 将指定文件夹下面的所有内容copy到目标文件夹下面 果目标文件夹为只读属性就会报错。
        /****************************************
          * 函数名称:CopyDir
          * 功能说明:将指定文件夹下面的所有内容copy到目标文件夹下面 果目标文件夹为只读属性就会报错。
          * 参     数:srcPath:原始路径,aimPath:目标文件夹
          * 调用示列:
          *            string srcPath = Server.MapPath("test/");  
          *            string aimPath = Server.MapPath("test1/");
          *            FileUtil.CopyDir(srcPath,aimPath);   
         *****************************************/
        /// <summary>
        /// 指定文件夹下面的所有内容copy到目标文件夹下面
        /// </summary>
        /// <param name="srcPath">原始路径</param>
        /// <param name="aimPath">目标文件夹</param>
        public static void CopyDir(string srcPath, string aimPath)
        {
            try
            {
                // 检查目标目录是否以目录分割字符结束如果不是则添加之
                if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar)
                    aimPath += Path.DirectorySeparatorChar;
                // 判断目标目录是否存在如果不存在则新建之
                if (!Directory.Exists(aimPath))
                    Directory.CreateDirectory(aimPath);
                // 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组
                //如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
                //string[] fileList = Directory.GetFiles(srcPath);
                string[] fileList = Directory.GetFileSystemEntries(srcPath);
                //遍历所有的文件和目录
                foreach (string file in fileList)
                {
                    //先当作目录处理如果存在这个目录就递归Copy该目录下面的文件

                    if (Directory.Exists(file))
                        CopyDir(file, aimPath + Path.GetFileName(file));
                    //否则直接Copy文件
                    else
                        File.Copy(file, aimPath + Path.GetFileName(file), true);
                }

            }
            catch (Exception ee)
            {
                throw new Exception(ee.ToString());
            }
        }


        #endregion
           #region 解压缩 文件
        /// <summary>
        /// 压缩文件 此方法要在服务器端安装解压缩软件
        /// </summary>
        /// <param name="unRarPatch"></param>
        /// <param name="rarPatch"></param>
        /// <param name="rarName"></param>
        public static void unCompressRAR(string unRarPatch, string rarPatch, string rarName)
        {
            try
            {
                string the_rar;
                RegistryKey the_Reg;
                object the_Obj;
                string the_Info;

                the_Reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe");
                the_Obj = the_Reg.GetValue("");
                the_rar = the_Obj.ToString();
                the_Reg.Close();
                //the_rar = the_rar.Substring(1, the_rar.Length - 7);

                if (Directory.Exists(unRarPatch) == false)
                {
                    Directory.CreateDirectory(unRarPatch);
                }
                the_Info = "x  -y  " + rarName + " " + unRarPatch;
                ProcessStartInfo the_StartInfo = new ProcessStartInfo();
                the_StartInfo.FileName = the_rar;
                the_StartInfo.Arguments = the_Info;
                the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                the_StartInfo.WorkingDirectory = rarPatch;//获取压缩包路径

                Process the_Process = new Process();
                the_Process.StartInfo = the_StartInfo;
                the_Process.Start();
                the_Process.WaitForExit();
                the_Process.Close();
            }
            catch (Exception e)
            {

                throw e;
            }
        }
        /// <summary>
        /// 将文件的绝对路径转为相对路径
        /// </summary>
        /// <param name="s"></param>
        /// <param name="ServerDir"></param>
        /// <returns></returns>
        public string ShortDir(string s, string ServerDir)
        {
            string d = s.Replace(ServerDir, "");
            return d;
        }
        /// <summary>
        /// 压缩文件 
        /// </summary>
        /// <param name="p">为客户端传回来的文件列表:文件名+压缩包的名称</param>
        /// <param name="ServerDir">保存路径</param>
        public void ZipFile(string p, string ServerDir)
        {
            string[] tmp = p.Split(new char[] { '*' });  //分离文件列表
            if (tmp[tmp.Length - 1] != "")  //压缩包名称不为空
            {
                ZipOutputStream u = new ZipOutputStream(File.Create(ServerDir + tmp[tmp.Length - 1]));            //新建压缩文件流 “ZipOutputStream”
                for (int i = 0; i < tmp.Length - 1; i++)
                {
                    if (tmp[i] != "")  //分离出来的文件名不为空
                    {
                        this.AddZipEntry(tmp[i], u, out u, ServerDir); //向压缩文件流加入内容
                    }
                }
                u.Finish(); // 结束压缩
                u.Close();
            }
        }
        /// <summary>
        /// 添加压缩项目:
        /// </summary>
        /// <param name="p"> p 为需压缩的文件或文件夹;</param>
        /// <param name="u"> u 为现有的源ZipOutputStream;</param>
        /// <param name="j">out j为已添加“ZipEntry”的“ZipOutputStream”</param>
        public void AddZipEntry(string p, ZipOutputStream u, out ZipOutputStream j, string ServerDir)
        {
            string s = ServerDir + p;

            if (Directory.Exists(s)) //文件夹的处理
            {
                DirectoryInfo di = new DirectoryInfo(s);

                //***********以下内容是修订后添加的***********

                if (di.GetDirectories().Length <= 0)   //没有子目录
                {
                    ZipEntry z = new ZipEntry(p + "\"\""); //末尾“""”用于文件夹的标记
                    u.PutNextEntry(z);
                }

                //***************以上内容是修订后添加的***************


                foreach (DirectoryInfo tem in di.GetDirectories()) //获取子目录
                {
                    ZipEntry z = new ZipEntry(this.ShortDir(tem.FullName, ServerDir) + "\"\""); //末尾“""”用于文件夹的标记
                    u.PutNextEntry(z);    //此句不可少,否则空目录不会被添加
                    s = this.ShortDir(tem.FullName, ServerDir);
                    this.AddZipEntry(s, u, out u, ServerDir);       //递归
                }
                foreach (FileInfo temp in di.GetFiles())  //获取此目录的文件
                {
                    s = this.ShortDir(temp.FullName, ServerDir);
                    this.AddZipEntry(s, u, out u, ServerDir);       //递归
                }
            }
            else if (File.Exists(s)) //文件的处理
            {
                u.SetLevel(9);      //压缩等级
                FileStream f = File.OpenRead(s);
                byte[] b = new byte[f.Length];
                f.Read(b, 0, b.Length);           //将文件流加入缓冲字节中
                ZipEntry z = new ZipEntry(this.ShortDir(s, ServerDir));
                u.PutNextEntry(z);              //为压缩文件流提供一个容器
                u.Write(b, 0, b.Length); //写入字节
                f.Close();
            }
            j = u;    //返回已添加数据的“ZipOutputStream”
        }
        /// <summary>
        /// 解压缩文件 
        /// </summary>
        /// <param name="p">为客户端传回来的文件列表'*'间隔</param>
        /// <param name="ServerDir">保存路径</param>
        public void UnZipFile(string p, string ServerDir)
        {
            string[] un_tmp = p.Split(new char[] { '*' });
            int i2 = 0;  //防止名称冲突的参数
            for (int j = 0; j < un_tmp.Length; j++)
            {
                if (un_tmp[j] != "")
                {
                    string un_time = System.DateTime.Now.ToShortDateString() + "-" + System.DateTime.Now.Hour.ToString() + "-" + System.DateTime.Now.Minute.ToString() + "-" + (System.DateTime.Now.Second + i2).ToString();
                    string un_dir = ServerDir + "Unzip-" + un_time;
                    Directory.CreateDirectory(un_dir);     //创建以解压时间为名称的文件夹
                    ZipInputStream f = new ZipInputStream(File.OpenRead(ServerDir + un_tmp[j])); //读取压缩文件,并用此文件流新建 “ZipInputStream”对象

                        A: ZipEntry zp = f.GetNextEntry();    //获取解压文件流中的项目。 另注(我的理解):在压缩包里每个文件都以“ZipEntry”形式存在,其中包括存放文件的目录信息。如果空目录被压缩,该目录下将出现一个名称为空、大小为 0 、“Crc”属性为 00000000 的“文件”。此文件只是个标记,不会被解压。

                    while (zp != null)
                    {
                        string un_tmp2;
                        if (zp.Name.IndexOf("\"\"") >= 0) //获取文件的目录信息
                        {
                            int tmp1 = zp.Name.LastIndexOf("\"\"");
                            un_tmp2 = zp.Name.Substring(0, tmp1);
                            Directory.CreateDirectory(un_dir + "\"\"" + un_tmp2 + "\"\""); //必须先创建目录,否则解压失败 --- (A) 关系到下面的步骤(B)
                        }
                        if (!zp.IsDirectory && zp.Crc != 00000000L) //此“ZipEntry”不是“标记文件”
                        {
                            int i = 2048;
                            byte[] b = new byte[i];  //每次缓冲 2048 字节
                            FileStream s = File.Create(un_dir + "\"\"" + zp.Name); //(B)-新建文件流
                            while (true) //持续读取字节,直到一个“ZipEntry”字节读完
                            {
                                i = f.Read(b, 0, b.Length); //读取“ZipEntry”中的字节
                                if (i > 0)
                                {
                                    s.Write(b, 0, i); //将字节写入新建的文件流
                                }
                                else
                                {
                                    break; //读取的字节为 0 ,跳出循环
                                }
                            }
                            s.Close();
                        }
                        goto A; //进入下一个“ZipEntry”
                    }
                    f.Close();
                    i2++;
                }
            }
        }
        #endregion
          public static void ListFiles(FileSystemInfo info, string toPath, string extenStr)
        {
            if (!info.Exists) return;
            DirectoryInfo dir = info as DirectoryInfo;
            //不是目录 
            if (dir == null) return;
            FileSystemInfo[] files = dir.GetFileSystemInfos();
            for (int i = 0; i < files.Length; i++)
            {
                FileInfo file = files[i] as FileInfo;

                if (file != null) //是文件 
                {
                    if (file.Extension.ToLower().Equals(extenStr.ToLower()))
                    {
                        FileCoppy(file.FullName, toPath + "/" + file.Name);
                    }
                }
                else//对于子目录,进行递归调用 
                    ListFiles(files[i], toPath, extenStr);
            }
        }

5.将泛型集合转换为datatable

  /// <summary>
        /// 将泛类型集合List类转换成DataTable
        /// </summary>
        /// <param name="list">泛类型集合</param>
        /// <returns></returns>
        public DataTable ListToDataTable<T>(List<T> entitys)
        {
            //检查实体集合不能为空
            if (entitys == null || entitys.Count < 1)
            {
                throw new Exception("需转换的集合为空");
            }
            //取出第一个实体的所有Propertie
            Type entityType = entitys[0].GetType();
            PropertyInfo[] entityProperties = entityType.GetProperties();

            //生成DataTable的structure
            //生产代码中,应将生成的DataTable结构Cache起来,此处略
            DataTable dt = new DataTable();
            for (int i = 0; i < entityProperties.Length; i++)
            {
                //dt.Columns.Add(entityProperties[i].Name, entityProperties[i].PropertyType);
                dt.Columns.Add(entityProperties[i].Name);
            }
            //将所有entity添加到DataTable中
            foreach (object entity in entitys)
            {
                //检查所有的的实体都为同一类型
                if (entity.GetType() != entityType)
                {
                    throw new Exception("要转换的集合元素类型不一致");
                }
                object[] entityValues = new object[entityProperties.Length];
                for (int i = 0; i < entityProperties.Length; i++)
                {
                    entityValues[i] = entityProperties[i].GetValue(entity, null);
                }
                dt.Rows.Add(entityValues);
            }
            return dt;
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值