INI配置文件读写工具类

INI配置文件读写工具类

using System;

using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.IO;

namespace Yong.CommonLib
{
    /// <summary>
    /// ini 配置文件读写
    /// TODO:应该使用“单例”来创建实例,以提高效率
    /// TODO:考虑使用Nini或Win32 api调用实现,好处:稳定代码,速度更快
    /// Nini还可以读取配置文件和注册表
    /// </summary>

    public class CIni
    {
        private StreamReader aStreamReader;
        private StreamWriter aStreamWriter;
        private ArrayList aSegList = new ArrayList();
        public string strLastError = "没有错误";
        private string strRoot = "";
        private string strKey = "";
        struct StructSeg
        {
            public string strSeg;
            public ArrayList ItemValue;
            public StructSeg(string strSeg)
            {
                this.strSeg = strSeg;
                ItemValue = new ArrayList();
            }
        }
        /// <summary>
        /// </summary>


        public CIni()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }
        /// <summary>
        /// TODO:使用map优化!
        /// </summary>
        /// <returns></returns>
        public int SetCrypto(string strSetKey)
        {
            byte[] aBytes = Encoding.GetEncoding("gb2312").GetBytes(strSetKey);
            if (aBytes.Length != 8 && aBytes.Length != 16)
            {
                strLastError = "密钥长度错误";
                return -1;
            }
            this.strKey = strSetKey;
            return 0;
        }
        public int SetRoot(string strSetRoot)
        {
            strSetRoot = strSetRoot.Trim();
            if (strSetRoot != "")
            {
                this.strRoot = strSetRoot + "\\";
            }
            else
            {
                this.strRoot = "";
            }
            return 0;
        }
        /// <summary>
        /// 获取所有段中同名的项目的值
        /// </summary>
        /// <returns></returns>
        public ArrayList getAllSegName()
        {
            ArrayList al = new ArrayList();
            foreach (StructSeg aSeg in aSegList)
            {
                al.Add(trimBracket(aSeg.strSeg));
            }
            return al;
        }
        private string trimBracket(string source)
        {
            int begin = source.IndexOf('[');
            int end = source.IndexOf(']');
            if (begin >= end || begin < 0 || end < 0)
            {
                return source;
            }
            return source.Substring(begin + 1, end - begin - 1);
        }
        public int LoadFromString(string strContent)
        {
            try
            {
                byte[] byteContent = Encoding.GetEncoding("gb2312").GetBytes(strContent);
                return LoadFromBytes(byteContent);
            }
            catch (Exception e)
            {
                strLastError = "加载失败,系统提示:" + e.Message;
                return (-1);
            }
            finally
            {
                try
                {
                    aStreamReader.Close();
                }
                catch
                {
                }
            }
        }
        public int LoadFromBytes(byte[] byteContent)
        {
            try
            {
                MemoryStream stream = new MemoryStream();
                stream.Write(byteContent, 0, byteContent.Length);
                stream.Flush();
                stream.Position = 0;
                aStreamReader = new StreamReader(stream, Encoding.GetEncoding("gb2312"));
                return Load();
            }
            catch (Exception e)
            {
                strLastError = "加载失败,系统提示:" + e.Message;
                return (-1);
            }
            finally
            {
                try
                {
                    aStreamReader.Close();
                }
                catch
                {
                }
            }

        }
        private int Load()
        {
            try
            {
                aSegList = new ArrayList();
                string strHead;
                string aLine;
                StructSeg aSeg = new StructSeg("[]");
                while ((aLine = aStreamReader.ReadLine()) != null)
                {
                    aLine = aLine.Trim().TrimEnd(new char[] { '\0' });
                    if (aLine.Length > 0)
                    {
                        strHead = aLine.Substring(0, 1);
                    }
                    else
                    {
                        continue;
                    }
                    if (strHead == "[")
                    {
                        aSegList.Add(aSeg);
                        aSeg = new StructSeg(aLine);
                    }
                    else
                    {
                        aSeg.ItemValue.Add(aLine);
                    }
                }
                aSegList.Add(aSeg);
                return 0;
            }
            catch (Exception e)
            {
                strLastError = "加载失败,系统提示:" + e.Message;
                return (-1);
            }
        }
        public int Load(string strFileName)
        {


            ClassCrypto aClassCrypto = null;
            try
            {
                if (strKey != "")
                {
                    aClassCrypto = new ClassCrypto(strKey);
                    if (aClassCrypto.GetCryptoStreamReader(strFileName) < 0)
                    {
                        strLastError = aClassCrypto.strLastError;
                        return -1;
                    }
                    aStreamReader = aClassCrypto.aReader;
                }
                else
                {
                    aStreamReader = new StreamReader(strFileName, Encoding.GetEncoding("gb2312"), true);
                }
                return Load();
            }
            catch (Exception e)
            {

                strLastError = "加载失败,系统提示:" + e.Message;
                return (-1);
            }
            finally
            {
                try
                {
                    if (strKey != "")
                    {

                        aClassCrypto.CloseReader();
                    }
                    else
                    {
                        aStreamReader.Close();
                    }
                }
                catch
                {
                }
            }
        }
        public int PushToString(out string strContent)
        {
            strContent = null;
            try
            {
                byte[] byteContent = null;
                if (PushToBytes(out byteContent) < 0)
                {
                    return -1;
                }
                strContent = Encoding.GetEncoding("gb2312").GetString(byteContent, 0, byteContent.Length).Trim(new char[] { '\0' });
                return 0;
            }
            catch (Exception e)
            {
                strLastError = "输出失败,系统提示:" + e.Message;
                return (-1);
            }
        }
        public int PushToBytes(out byte[] byteContent)
        {
            byteContent = null;
            try
            {
                MemoryStream stream = new MemoryStream();
                aStreamWriter = new StreamWriter(stream, Encoding.GetEncoding("gb2312"));
                Push();
                byteContent = stream.ToArray();
                return 0;
            }
            catch (Exception e)
            {
                strLastError = "输出失败,系统提示:" + e.Message;
                return (-1);
            }
            finally
            {
                try
                {
                    aStreamWriter.Close();
                }
                catch
                {
                }
            }
        }

        public int Push(string strFileName)
        {
            ClassCrypto aClassCrypto = null;
            try
            {
                if (strKey != "")
                {
                    aClassCrypto = new ClassCrypto(strKey);
                    if (aClassCrypto.GetCryptoStreamWriter(strFileName) < 0)
                    {
                        strLastError = aClassCrypto.strLastError;
                        return -1;
                    }
                    aStreamWriter = aClassCrypto.aWriter;
                }
                else
                {
                    aStreamWriter = new StreamWriter(strFileName, false, Encoding.GetEncoding("gb2312"));

                }
                return Push();
            }
            catch (Exception e)
            {

                strLastError = "写文件失败,系统提示:" + e.Message;
                return (-1);
            }
            finally
            {
                if (strKey != "")
                {
                    aClassCrypto.CloseWriter();
                }
                else
                {
                    aStreamWriter.Close();
                }
            }
        }
        private int Push()
        {
            try
            {
                foreach (StructSeg aSeg in aSegList)
                {
                    if (aSeg.strSeg != "[]") aStreamWriter.WriteLine(aSeg.strSeg);
                    //System.Windows.Forms.MessageBox.Show(aSeg.strSeg);
                    foreach (string aLine in aSeg.ItemValue)
                    {
                        //System.Windows.Forms.MessageBox.Show(aLine);
                        aStreamWriter.WriteLine(aLine);
                    }
                }
                aStreamWriter.Flush();
                return 0;
            }
            catch (Exception e)
            {
                strLastError = "输出失败,系统提示:" + e.Message;
                return (-1);
            }
        }
        public int GetIniItem(string strSeg, string strItem, out string strValue)
        {
            strSeg = "[" + strRoot + strSeg.Trim() + "]";
            strValue = "";
            try
            {
                foreach (StructSeg aSeg in aSegList)
                {
                    if (GetSeg(aSeg.strSeg).ToUpper() == strSeg.ToUpper())
                    {
                        foreach (string aLine in aSeg.ItemValue)
                        {
                            if (GetItem(aLine).ToUpper() == strItem.ToUpper())
                            {
                                strValue = GetValue(aLine);
                                return (0);
                            }
                        }
                    }
                }
                strLastError = "未找到数据:" + strSeg + " " + strItem;
                return (-1);
            }
            catch (Exception e)
            {
                strLastError = "获取数据异常:" + strSeg + " " + strItem + " 系统提示:" + e.Message;
                return (-2);
            }
        }
        public int GetIniItemBlock(string strSeg, string strItem, out byte[] bytesValue)
        {
            strSeg = "[" + strRoot + strSeg.Trim() + "]";
            bytesValue = new byte[0];
            string strValue = "";
            try
            {
                foreach (StructSeg aSeg in aSegList)
                {
                    if (GetSeg(aSeg.strSeg).ToUpper() == strSeg.ToUpper())
                    {
                        for (int i = 0; i < aSeg.ItemValue.Count; i++)
                        {
                            string aLine = (string)aSeg.ItemValue[i];
                            if (GetItem(aLine).ToUpper() == strItem.ToUpper())
                            {
                                strValue = GetValue(aLine);
                                if (strValue.EndsWith("-"))
                                {
                                    strValue = strValue.Substring(0, strValue.Length - 1);
                                    for (int j = i + 1; j < aSeg.ItemValue.Count; j++)
                                    {
                                        aLine = (string)aSeg.ItemValue[j];
                                        aLine = aLine.Trim();
                                        if (!aLine.StartsWith(";-")) break;
                                        aLine = aLine.Substring(2);
                                        strValue += aLine;
                                        if (!strValue.EndsWith("-")) break;
                                        strValue = strValue.Substring(0, strValue.Length - 1);
                                    }
                                }
                                try
                                {
                                    bytesValue = Convert.FromBase64String(strValue);
                                }
                                catch (Exception e)
                                {
                                    strLastError = "数据处理异常:" + strSeg + " " + strItem + " 系统提示:" + e.Message;
                                    return (-1);
                                }
                                //if(HexToBytes(strValue,out bytesValue)!=0){
                                //    return (-1);
                                //}
                                return (0);
                            }
                        }
                    }
                }
                strLastError = "未找到数据:" + strSeg + " " + strItem;
                return (-1);
            }
            catch (Exception e)
            {
                strLastError = "获取数据异常:" + strSeg + " " + strItem + " 系统提示:" + e.Message;
                return (-2);
            }
        }
        public int GetIniItem(string strSeg, string strItem, out int iValue)
        {
            string strValue;
            iValue = 0;
            int iRetCode = GetIniItem(strSeg, strItem, out strValue);
            if (iRetCode < 0) return (iRetCode);
            try
            {
                iValue = Convert.ToInt32(strValue);
            }
            catch
            {
            }
            return (0);
        }
        public int GetIniItem(string strSeg, string strItem, out Single sValue)
        {
            string strValue;
            sValue = 0f;
            int iRetCode = GetIniItem(strSeg, strItem, out strValue);
            if (iRetCode < 0) return (iRetCode);
            try
            {
                sValue = Convert.ToSingle(strValue);
            }
            catch
            {
            }
            return (0);
        }
        public int GetIniItem(string strSeg, string strItem, out bool bValue)
        {
            string strValue;
            bValue = false;
            int iRetCode = GetIniItem(strSeg, strItem, out strValue);
            if (iRetCode < 0) return (iRetCode);
            if (strValue == "true" || strValue == "TRUE" || strValue == "True" ||
                strValue == "是" ||
                strValue == "yes" || strValue == "YES" || strValue == "Yes")
            {
                bValue = true;
            }
            else
            {
                bValue = false;
            }
            return (0);
        }
        public int GetIniItem(string strSeg, string strItem, out byte[] byetsValue)
        {
            string strValue;
            byetsValue = new byte[0];
            int iRetCode = GetIniItem(strSeg, strItem, out strValue);
            if (iRetCode < 0) return (iRetCode);
            return (HexToBytes(strValue, out byetsValue));
        }
        public int SetIniItem(string strSeg, string strItem, byte[] bytesValue)
        {
            return (SetIniItem(strSeg, strItem, bytesValue, ""));
        }
        public int SetIniItem(string strSeg, string strItem, byte[] bytesValue, string strDescription)
        {
            string strHex;
            int iRetCode = BytesToHex(out strHex, bytesValue);
            if (iRetCode < 0) return (iRetCode);
            return (SetIniItem(strSeg, strItem, strHex, strDescription));
        }
        public int SetIniItem(string strSeg, string strItem, bool bValue)
        {
            return (SetIniItem(strSeg, strItem, bValue, ""));
        }

        public int SetIniItem(string strSeg, string strItem, bool bValue, string strDescription)
        {
            return (SetIniItem(strSeg, strItem, bValue.ToString(), strDescription));
        }
        public int SetIniItem(string strSeg, string strItem, string strValue)
        {
            return (SetIniItem(strSeg, strItem, strValue, ""));
        }
        public int SetIniItem(string strSeg, string strItem, string strValue, string strDescription)
        {
            strSeg = "[" + strRoot + strSeg.Trim() + "]";
            strValue = CheckValue(strValue);
            string aNewLine = strItem + "\t=\t" + strValue;
            StructSeg aSeg;
            int i, j;
            string aLine;
            try
            {
                for (i = 0; i < aSegList.Count; i++)
                {
                    aSeg = (StructSeg)aSegList[i];
                    if (GetSeg(aSeg.strSeg).ToUpper() == strSeg.ToUpper())
                    {
                        for (j = 0; j < aSeg.ItemValue.Count; j++)
                        {
                            aLine = (string)aSeg.ItemValue[j];
                            if (GetItem(aLine).ToUpper() == strItem.ToUpper())
                            {
                                if (strDescription != "")
                                {
                                    aNewLine = aNewLine + "\t;" + strDescription;
                                }
                                else if (GetDescription(aLine) != "")
                                {
                                    aNewLine = aNewLine + "\t;" + GetDescription(aLine);
                                }
                                aSeg.ItemValue[j] = aNewLine;
                                aSegList[i] = aSeg;
                                return (0);
                            }
                        }
                        if (strDescription != "") aNewLine = aNewLine + "\t;" + strDescription;
                        aSeg.ItemValue.Add(aNewLine);
                        aSegList[i] = aSeg;
                        return (0);
                    }
                }
                aSeg = new StructSeg(strSeg);
                if (strDescription != "") aNewLine = aNewLine + "\t;" + strDescription;
                aSeg.ItemValue.Add(aNewLine);
                aSegList.Add(aSeg);
                return (0);
            }
            catch (Exception e)
            {
                strLastError = "设置数据异常:" + strSeg + " " + strItem + " 系统提示:" + e.Message;
                return (-2);
            }
        }
        public int SetIniItemBlock(string strSeg, string strItem, byte[] bytesValue)
        {
            strSeg = "[" + strRoot + strSeg.Trim() + "]";
            string strValue;
            string[] strArray = new string[0];
            //if (BytesToHex(out strValue, bytesValue) != 0) return -1;
            try
            {
                strValue = Convert.ToBase64String(bytesValue);
            }
            catch (Exception e)
            {
                strLastError = "数据处理异常:" + strSeg + " " + strItem + " 系统提示:" + e.Message;
                return -1;
            }
            string aNewLine = strItem + "\t=\t-";
            int i, j;
            i = (strValue.Length + 63) / 64;
            if (i > 0)
            {
                strArray = new string[i];
                for (j = 0; j < (i - 1); j++)
                {
                    strArray[j] = ";-" + strValue.Substring(j * 64, 64) + "-";
                }
                strArray[i - 1] = ";-" + strValue.Substring((i - 1) * 64);
            }
            StructSeg aSeg;
            string aLine;
            try
            {
                for (i = 0; i < aSegList.Count; i++)
                {
                    aSeg = (StructSeg)aSegList[i];
                    if (GetSeg(aSeg.strSeg).ToUpper() == strSeg.ToUpper())
                    {
                        for (j = 0; j < aSeg.ItemValue.Count; j++)
                        {
                            aLine = (string)aSeg.ItemValue[j];
                            if (GetItem(aLine).ToUpper() == strItem.ToUpper())
                            {
                                aSeg.ItemValue[j] = aNewLine;
                                for (int k = j + 1; k < aSeg.ItemValue.Count; k++)
                                {
                                    aLine = (string)aSeg.ItemValue[k];
                                    aLine = aLine.Trim();
                                    if (aLine.StartsWith(";-"))
                                    {
                                        aSeg.ItemValue.RemoveAt(k);
                                        k--;
                                        continue;
                                    }
                                }
                                for (int k = 0; k < strArray.Length; k++)
                                {
                                    aSeg.ItemValue.Insert(j + k + 1, strArray[k]);
                                }
                                aSegList[i] = aSeg;
                                return (0);
                            }
                        }
                        aSeg.ItemValue.Add(aNewLine);
                        for (int k = 0; k < strArray.Length; k++)
                        {
                            aSeg.ItemValue.Add(strArray[k]);
                        }
                        aSegList[i] = aSeg;
                        return (0);
                    }
                }
                aSeg = new StructSeg(strSeg);
                aSeg.ItemValue.Add(aNewLine);
                for (int k = 0; k < strArray.Length; k++)
                {
                    aSeg.ItemValue.Add(strArray[k]);
                }
                aSegList[i] = aSeg;
                aSegList.Add(aSeg);
                return (0);
            }
            catch (Exception e)
            {
                strLastError = "设置数据异常:" + strSeg + " " + strItem + " 系统提示:" + e.Message;
                return (-2);
            }
        }
        public int RemoveIniItem(string strSeg, string strItem)
        {
            strSeg = "[" + strRoot + strSeg.Trim() + "]";
            StructSeg aSeg;
            int i, j;
            string aLine;
            try
            {
                for (i = 0; i < aSegList.Count; i++)
                {
                    aSeg = (StructSeg)aSegList[i];
                    if (GetSeg(aSeg.strSeg).ToUpper() == strSeg.ToUpper())
                    {
                        for (j = 0; j < aSeg.ItemValue.Count; j++)
                        {
                            aLine = (string)aSeg.ItemValue[j];
                            if (GetItem(aLine).ToUpper() == strItem.ToUpper())
                            {
                                aSeg.ItemValue.RemoveAt(j);
                                aSegList[i] = aSeg;
                                break;
                            }
                        }
                        if (aSeg.ItemValue.Count <= 0)
                        {
                            aSegList.RemoveAt(i);
                        }
                        break;
                    }
                }
                return (0);
            }
            catch (Exception e)
            {
                strLastError = "删除数据异常:" + strSeg + " " + strItem + " 系统提示:" + e.Message;
                return (-2);
            }
        }
        private string Clear(string aLine)
        {
            int iPos = 0;
            while ((iPos = aLine.IndexOf(';', iPos)) >= 0)
            {
                if (iPos == 0) break;
                if (aLine.Substring(iPos - 1, 1) != "\\") break;
                iPos++;
            }
            if (iPos >= 0) aLine = aLine.Substring(0, iPos);
            aLine = aLine.Trim();
            return (aLine);
        }
        private string GetSeg(string aLine)
        {
            aLine = Clear(aLine);
            return (aLine);
        }
        private string GetItem(string aLine)
        {
            aLine = Clear(aLine);
            string[] strArray = aLine.Split("=".ToCharArray());
            return (strArray[0].Trim());
        }
        private string GetValue(string aLine)
        {
            aLine = Clear(aLine);
            int iPos = aLine.IndexOf("=");
            if (iPos >= 0 && iPos < (aLine.Length - 1))
            {
                aLine = aLine.Substring(iPos + 1).Trim() + " ";
                iPos = 0;
                while ((iPos = aLine.IndexOf('\\', iPos)) >= 0)
                {
                    switch (aLine.Substring(iPos + 1, 1))
                    {
                        case "r":
                            aLine = aLine.Substring(0, iPos) + "\r" + aLine.Substring(iPos + 2);
                            break;
                        case "n":
                            aLine = aLine.Substring(0, iPos) + "\n" + aLine.Substring(iPos + 2);
                            break;
                        case "t":
                            aLine = aLine.Substring(0, iPos) + "\t" + aLine.Substring(iPos + 2);
                            break;
                        default:
                            aLine = aLine.Substring(0, iPos) + aLine.Substring(iPos + 1);
                            break;
                    }
                    iPos += 1;
                }
                return (aLine.Trim());
            }
            else
            {
                return ("");
            }
        }
        private string CheckValue(string strValue)
        {
            int iPos = 0;
            while ((iPos = strValue.IndexOf('\\', iPos)) >= 0)
            {
                strValue = strValue.Substring(0, iPos) + "\\" + strValue.Substring(iPos);
                iPos += 2;
            }
            iPos = 0;
            while ((iPos = strValue.IndexOf(';', iPos)) >= 0)
            {
                strValue = strValue.Substring(0, iPos) + "\\" + strValue.Substring(iPos);
                iPos += 2;
            }
            iPos = 0;
            while ((iPos = strValue.IndexOf('\r', iPos)) >= 0)
            {
                strValue = strValue.Substring(0, iPos) + "\\r" + strValue.Substring(iPos + 1);
                iPos += 3;
                if (iPos >= strValue.Length) break;
            }
            iPos = 0;
            while ((iPos = strValue.IndexOf('\n', iPos)) >= 0)
            {
                strValue = strValue.Substring(0, iPos) + "\\n" + strValue.Substring(iPos + 1);
                iPos += 3;
                if (iPos >= strValue.Length) break;
            }
            iPos = 0;
            while ((iPos = strValue.IndexOf('\t', iPos)) >= 0)
            {
                strValue = strValue.Substring(0, iPos) + "\\t" + strValue.Substring(iPos + 1);
                iPos += 3;
                if (iPos >= strValue.Length) break;
            }
            return (strValue);
        }
        private string GetDescription(string aLine)
        {
            int iPos = 0;
            while ((iPos = aLine.IndexOf(';', iPos)) >= 0)
            {
                if (iPos == 0) break;
                if (aLine.Substring(iPos - 1, 1) != "\\") break;
                iPos++;
            }
            if (iPos >= 0)
            {
                aLine = aLine.Substring(iPos + 1);
            }
            else
            {
                aLine = "";
            }
            aLine = aLine.Trim();
            return (aLine);
        }
        /// <summary>
        /// TODO:应该放在公共库中
        /// </summary>
        /// <param name="strHex"></param>
        /// <param name="aBytes"></param>
        /// <returns></returns>
        public int HexToBytes(string strHex, out byte[] aBytes)
        {
            strHex = strHex.ToUpper();
            char[] tmpCharArray = strHex.ToCharArray();
            aBytes = new byte[0];
            if ((tmpCharArray.Length % 2) != 0)
            {
                strLastError = "HEX数据长度错误";
                return (-1);
            }
            aBytes = new byte[tmpCharArray.Length / 2];
            for (int i = 0; i < tmpCharArray.Length; i += 2)
            {
                if (tmpCharArray[i] >= 'A' && tmpCharArray[i] <= 'F')
                {
                    aBytes[i / 2] = (byte)((tmpCharArray[i] - 'A' + 10) * 16);
                }
                else if (tmpCharArray[i] >= '0' && tmpCharArray[i] <= '9')
                {
                    aBytes[i / 2] = (byte)((tmpCharArray[i] - '0') * 16);
                }
                else
                {
                    strLastError = "HEX数据中有非法字符";
                    return (-1);
                }
                if (tmpCharArray[i + 1] >= 'A' && tmpCharArray[i + 1] <= 'F')
                {
                    aBytes[i / 2] += (byte)((tmpCharArray[i + 1] - 'A' + 10));
                }
                else if (tmpCharArray[i + 1] >= '0' && tmpCharArray[i + 1] <= '9')
                {
                    aBytes[i / 2] += (byte)((tmpCharArray[i + 1] - '0'));
                }
                else
                {
                    strLastError = "HEX数据中有非法字符";
                    return (-1);
                }
            }
            return (0);
        }
        /// <summary>
        /// TODO:应该放在公共库中
        /// </summary>
        /// <param name="strHex"></param>
        /// <param name="aBytes"></param>
        /// <returns></returns>
        public int BytesToHex(out string strHex, byte[] aBytes)
        {
            strHex = "";
            int iBlock = aBytes.Length / 16;
            int i, j;
            for (j = 0; j < iBlock; j++)
            {
                i = j * 16;
                strHex += String.Format("{0:X2}{1:X2}{2:X2}{3:X2}{4:X2}{5:X2}{6:X2}{7:X2}{8:X2}{9:X2}{10:X2}{11:X2}{12:X2}{13:X2}{14:X2}{15:X2}",
                    aBytes[i], aBytes[i + 1], aBytes[i + 2], aBytes[i + 3], aBytes[i + 4], aBytes[i + 5], aBytes[i + 6], aBytes[i + 7],
                    aBytes[i + 8], aBytes[i + 9], aBytes[i + 10], aBytes[i + 11], aBytes[i + 12], aBytes[i + 13], aBytes[i + 14], aBytes[i + 15]);
            }
            for (i = iBlock * 16; i < aBytes.Length; i++)
            {
                strHex += String.Format("{0:X2}", aBytes[i]);
            }
            return (0);
        }

    }
}

ClassCryptole类:

using System;

using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace Yong.CommonLib
{
    public class ClassCrypto
    {
        private string strKey = "12345678";
        public StreamReader aReader;
        public StreamWriter aWriter;
        private FileStream aFileStreamRead;
        private FileStream aFileStreamWrite;
        private CryptoStream aCryptoStreamRead;
        private CryptoStream aCryptoStreamWrite;
        private DESCryptoServiceProvider aDes;
        public string strLastError = "";
        public ClassCrypto()
        {
            aDes = new DESCryptoServiceProvider();
            aDes.Key = Encoding.ASCII.GetBytes(strKey);
            aDes.IV = Encoding.ASCII.GetBytes(strKey);
        }
        public ClassCrypto(string _strKey)
        {
            strKey = _strKey;
            aDes = new DESCryptoServiceProvider();
            aDes.Key = Encoding.ASCII.GetBytes(strKey);
            aDes.IV = Encoding.ASCII.GetBytes(strKey);
        }
        public int GetCryptoStreamReader(string strFileName)
        {
            return GetCryptoStreamReader(strFileName, Encoding.Default);
        }
        public int GetCryptoStreamReader(string strFileName, Encoding aEncoding)
        {
            try
            {
                ICryptoTransform desencrypt = aDes.CreateDecryptor();
                aFileStreamRead = new FileStream(strFileName, FileMode.Open);
                aCryptoStreamRead = new CryptoStream(aFileStreamRead, desencrypt, CryptoStreamMode.Read);
                aReader = new StreamReader(aCryptoStreamRead, aEncoding, true);
                return 0;
            }
            catch (Exception e)
            {
                strLastError = "在打开文件" + strFileName + "时发生异常" + e.Message;
                return -1;
            }
        }
        public int GetCryptoStreamReader(string strFileName, Encoding aEncoding, int bufferSize)
        {
            try
            {
                ICryptoTransform desencrypt = aDes.CreateDecryptor();
                aFileStreamRead = new FileStream(strFileName, FileMode.Open);
                aCryptoStreamRead = new CryptoStream(aFileStreamRead, desencrypt, CryptoStreamMode.Read);
                aReader = new StreamReader(aCryptoStreamRead, aEncoding, true, bufferSize);
                return 0;
            }
            catch (Exception e)
            {
                strLastError = "在打开文件" + strFileName + "时发生异常" + e.Message;
                return -1;
            }
        }
        public int GetCryptoStreamWriter(string strFileName)
        {
            return GetCryptoStreamWriter(strFileName, false, Encoding.Default);
        }
        public int GetCryptoStreamWriter(string strFileName, bool append, Encoding aEncoding)
        {
            try
            {
                ICryptoTransform desencrypt = aDes.CreateEncryptor();
                if (append)
                {
                    aFileStreamWrite = new FileStream(strFileName, FileMode.Append);
                }
                else
                {
                    aFileStreamWrite = new FileStream(strFileName, FileMode.Create);
                }
                aCryptoStreamWrite = new CryptoStream(aFileStreamWrite, desencrypt, CryptoStreamMode.Write);
                aWriter = new StreamWriter(aCryptoStreamWrite, aEncoding);
                return 0;
            }
            catch (Exception e)
            {
                strLastError = "在打开文件" + strFileName + "时发生异常" + e.Message;
                return -1;
            }
        }
        public int CloseWriter()
        {
            try
            {
                aWriter.Close();
            }
            catch
            {
            } try
            {
                aCryptoStreamWrite.Close();
            }
            catch { }
            try
            {
                aFileStreamWrite.Close();
            }
            catch (Exception e)
            {
                strLastError = "在关闭输出文件时发生异常:" + e.Message;
                return -1;
            }
            return 0;
        }
        public int CloseReader()
        {
            try
            {
                aReader.Close();
            }
            catch { }
            try
            {
                aCryptoStreamRead.Close();
            }
            catch { }
            try
            {
                aFileStreamRead.Close();
            }
            catch (Exception e)
            {
                strLastError = "在关闭输入文件时发生异常:" + e.Message;
                return -1;
            }
            return 0;
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值