[c#]常用工具类收集

1.  数字金额转中文

        /// <summary>
        /// 单个数字对应的中文
        /// </summary>
        /// <param name="n">单个数字</param>
        /// <returns>中文数字</returns>
        public static char GetUpperDigit(char n)
        {
           if (false==char.IsDigit(n))
            {
                return n;
            }
            switch (n)
            {
                case '1':
                    return '壹';
                case '2':
                    return '贰';
                case '3':
                    return '叁';
                case '4':
                    return '肆';
                case '5':
                    return '伍';
                case '6':
                    return '陆';
                case '7':
                    return '柒';
                case '8':
                    return '捌';
                case '9':
                    return '玖';
                default:
                    return '零';
            }
        }

        /// <summary>
        /// 获取中文数字
        /// </summary>
        /// <param name="digits">数字串(整数,亿以内)</param>
        /// <returns></returns>
        public static string GetUpperDigits(string digits)
        {
            var sb = new StringBuilder();
            for (int i = 0; i < digits.Length; i++)
            {
                char digitChar = digits[i];
                if (digitChar != '0'
                    || digits.Length == 1
                    || (i - 1 >= 0 && digits[i - 1] != '0' && i + 1 < digits.Length && digits[i + 1] != '0'))
                {
                    sb.Append(GetUpperDigit(digitChar));
                }
                if (digitChar == '0')
                {
                    continue;
                }
                switch ((digits.Length - i - 1) % 6)
                {
                    case 1:
                        sb.Append("拾");
                        break;
                    case 2:
                        sb.Append("佰");
                        break;
                    case 3:
                        sb.Append("仟");
                        break;
                    case 4:
                        sb.Append("万");
                        break;
                    case 5:
                        sb.Append("亿");
                        break;
                }
            }
            return sb.ToString();
        }

2.  FTP下载文件

public static void Download(string sourceFilePath, string desFilePath, string fileName,string ftpUser,string ftpPwd)
        {
            FtpWebRequest reqFTP;
            FileStream outputStream = null;

            try
            {
                if (!Directory.Exists(desFilePath))
                {
                    Directory.CreateDirectory(desFilePath);
                }
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(sourceFilePath + "/" + fileName));
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);
                reqFTP.Timeout = 40000;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                long cl = response.ContentLength;
                int bufferSize = 2048;
                int readCount;
                byte[] buffer = new byte[bufferSize];
                outputStream = new FileStream(desFilePath + "\\" + fileName, FileMode.Create);
                readCount = ftpStream.Read(buffer, 0, bufferSize);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }

                ftpStream.Close();
                outputStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                if (outputStream != null)
                {
                    outputStream.Close();
                }
            }
        }

3. 压缩及解压

         // 读入大小
        const int SIZE = 10240;
        
        /// <summary>
        /// 编码方式
        /// </summary>
        public readonly static Encoding GZipEncoding = Encoding.UTF8;
         
        /// <summary>
        /// 解压缩
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string Decompress(byte[] compressBuffer)
        { 
            using (MemoryStream msDecompress = new MemoryStream())
            {
                var gzip = new GZipStream(new MemoryStream(compressBuffer), CompressionMode.Decompress);
                int len = 0;
                byte[] buffer = new byte[SIZE];
                while ((len = gzip.Read(buffer, 0, buffer.Length)) != 0)
                {
                    msDecompress.Write(buffer, 0, len);
                }
                gzip.Close();
                return GZipEncoding.GetString(msDecompress.ToArray());
            }
        } 

        /// <summary>
        /// 压缩
        /// </summary>
        /// <param name="buffer">要压缩的字节</param>
        /// <returns></returns>
        public static MemoryStream Compress(byte[] buffer)
        {
            var ms = new MemoryStream();
            var compressedzipStream = new GZipStream(ms, CompressionMode.Compress, true);
            compressedzipStream.Write(buffer, 0, buffer.Length);
            compressedzipStream.Close();
            return ms;
        } 

4. 取文件MD5值

        /// <summary>
        ///  计算指定文件的MD5值
        /// </summary>
        /// <param name="fileName">指定文件的完全限定名称</param>
        /// <returns>返回值的字符串形式</returns>
        public static String ComputeMD5(String fileName)
        {
            String hashMD5 = String.Empty;
            //检查文件是否存在,如果文件存在则进行计算,否则返回空值
            if (File.Exists(fileName))
            {
                using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    //计算文件的MD5值
                    System.Security.Cryptography.MD5 calculator = System.Security.Cryptography.MD5.Create();
                    Byte[] buffer = calculator.ComputeHash(fs);
                    calculator.Clear();
                    //将字节数组转换成十六进制的字符串形式
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i < buffer.Length; i++)
                    {
                        stringBuilder.Append(buffer[i].ToString("x2"));
                    }
                    hashMD5 = stringBuilder.ToString();
                }//关闭文件流
            }//结束计算
            return hashMD5;
        }

5. 简单的HTTP下载

        /// <summary>
        /// http下载
        /// </summary>
        /// <param name="url"></param>
        /// <param name="encoding">字符编码</param>
        /// <returns></returns>
        public static string GetContent(string url,int timeout = 60000)
        {
            string content = string.Empty;
            try
            {
                var request = HttpWebRequest.Create(url) as HttpWebRequest;
                request.Timeout = timeout;
                request.Method = "GET";
                request.Headers = headers;
                var response = request.GetResponse() as HttpWebResponse;
                using (var sr = new StreamReader(response.GetResponseStream(), httpEncoding))
                {
                    content = sr.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("{0} {1}", ex.Message, url));
            }
            return content;
        }

6.  以http方式调用对方接口(post+json)

        /// <summary>  
        /// 创建POST方式的HTTP请求  
        /// </summary>  
        public static string PostHttpResponse(string url, string jsonStr)
        {
            byte[] data = Encoding.UTF8.GetBytes(jsonStr);

            //设置https验证方式
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback =
                        new RemoteCertificateValidationCallback(CheckValidationResult);
            }
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "POST";
            request.ContentLength = data.Length;
            request.ContentType = "application/x-www-form-urlencoded";

            //发送POST数据  
            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }
            return GetResponseString(request.GetResponse() as HttpWebResponse);
        }
        
        /// <summary>
        /// 获取请求的数据
        /// </summary>
        private static string GetResponseString(HttpWebResponse webresponse)
        {
            using (Stream s = webresponse.GetResponseStream())
            {
                StreamReader reader = new StreamReader(s, Encoding.UTF8);
                return reader.ReadToEnd();

            }
        }
        
        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            //直接确认,否则打不开    
            return true;
        }

7.  导出list对象到Excel(com方法调用,导大数据量时会很慢)

        /// <summary>
        /// 导出list对象到excel
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <param name="subPathName"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static bool SaveToExcel<T>(List<T> list,string subPathName, out string msg)
        {
            msg = "";
            object misValue = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            Workbook xlWorkBook = xlApp.Workbooks.Add(misValue);
            int iSheet = 1;
            Worksheet xlWorkSheet = (Worksheet)xlWorkBook.Worksheets.get_Item(iSheet);
            string filePath = Path.Combine(Directory.GetCurrentDirectory(), string.Format("excel\\{0}\\{1}.xls", subPathName, DateTime.Now.ToString("yyyyMMddHHssmm")));
            if (!Directory.Exists(Path.GetDirectoryName(filePath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(filePath));
            }
            bool isSuceess = true;

            PropertyInfo[] props = typeof(T).GetProperties();
            for (int j = 0; j < list.Count; j++)
            {
                for (int i = 0; i < props.Length; i++)
                {
                    if (0 == j)
                    {
                        //如果属性有描述,则取描述为标题
                        if (props[i].IsDefined(typeof(DescriptionAttribute), true))
                        {
                            object[] descObjs = props[i].GetCustomAttributes(typeof(DescriptionAttribute), true);
                            xlWorkSheet.Cells[1, i + 1] = ((DescriptionAttribute)descObjs[0]).Description;
                        }
                        else
                        {
                            xlWorkSheet.Cells[1, i + 1] = props[i].Name;
                        }
                    }
                    object value = props[i].GetValue(list[j], null) ?? string.Empty;
                    xlWorkSheet.Cells[j + 2, i + 1] = value;
                }
                if (j > 0 && 0 == j % 60000)//office2003 一个Sheet不能超过65535行
                {
                    xlWorkSheet = (Worksheet)xlWorkBook.Worksheets.get_Item(++iSheet);
                }
            }
            try
            {
                xlWorkBook.SaveAs(Filename: filePath, FileFormat: XlFileFormat.xlWorkbookNormal);
                xlWorkBook.Close(true, misValue, misValue);
                xlWorkBook = null;
                xlApp.Quit();
                xlApp = null;
                msg = filePath;
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                xlWorkBook.Close(true, misValue, misValue);
                xlApp.Quit();
                isSuceess = false;
            }
            finally
            {
                GC.Collect();//垃圾回收
                GC.WaitForPendingFinalizers();
            }

            return isSuceess;
        }

标签