C# 文件操作 通用接口(Ini,Xml,Json)


简介

大致思路:
1.定义一个IFileBase接口,提供文件基本操作,各个文件操作基于它来实现接口。
2.定义FileHelper类,类中定义一个接口变量 IFileBase file用于不同文件操作
3.不同文件类:XMLHalper,INIHalper,JsonHalper实现IFileBase接口对不同文件进行操作


一、IFileBase接口

代码如下:

    public interface IFileBase
    {

        /// <summary>
        /// 写文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tableName"></param>
        /// <param name="id"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        short Write<T>(string tableName, string id, T data);

        /// <summary>
        /// 写文件
        /// </summary>
        /// <param name="path"></param>
        /// <param name="Section"></param>
        /// <param name="Key"></param>
        /// <param name="Value"></param>
        short WriteINI(string path, string Section, string Key, string Value);

        /// <summary>
        /// 读取文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tablename"></param>
        /// <returns></returns>
         short Read<T>(string tablename,ref T Value);

        /// <summary>
        /// 读取文件
        /// </summary>
        /// <param name="tablename">路径名</param>
        /// <param name="id">节点名</param>
        /// <param name="Key">键名</param>
        /// <returns></returns>
        short ReadINI(string tablename, string id, string Key,ref string data);

    }

二、FileHelper文件操作类

不涉及文件的具体操作,只用设置对应的文件类型,调用接口即可

   public enum FileType
    {
        INIFile=0,
        XMLFile,
        JSONFile,
    }

代码如下:

   public class FileHelper : IFileHalperBase
    {
        public FileType type = FileType.INIFile;
        IFileBase file = new INIHalper();
        public FileHelper()
        {
        }

        public FileHelper(FileType fileType)
        {
            type = fileType;
            switch (fileType)
            {
                case FileType.INIFile:
                    file = new INIHalper();
                    break;
                case FileType.XMLFile:
                    file = new XMLHalper();
                    break;

                case FileType.JSONFile:
                    file = new JsonHalper();
                    break;

                default:
                    break;
            }
        }

        public void SetType(string dbType)
        {
            type = (FileType)Enum.Parse(typeof(FileType),dbType);
            switch (type)
            {
                case FileType.INIFile:
                    file = new INIHalper();
                    break;
                case FileType.XMLFile:
                    file = new XMLHalper();
                    break;

                case FileType.JSONFile:
                    file = new JsonHalper();
                    break;

                default:
                    break;
            }
        }



        public short Read<T>(string tablename, string id, ref T data)
        {
            return file.Read<T>(tablename, ref data);
        }

        public short Write<T>(string tableName, string id, T data)
        {
            if (!File.Exists(tableName))
            {
                File.Create(tableName);
            }
            return file.Write<T>(tableName, id, data);
        }

        public short Write<T>(string tableName, string id, List<T> data)
        {
            throw new NotImplementedException();
        }

        public short ReadList<T>(string tablename, ref List<T> data)
        {
            throw new NotImplementedException();
        }


        public short ReadINI(string tablename, string id, string Key, ref string Value)
        {
            return file.ReadINI(tablename, id,  Key, ref Value);
        }

        public short WriteINI(string path, string Section, string Key, string Value)
        {
            if (!File.Exists(path))
            {
                return -1;
            }
            return file.WriteINI(path, Section, Key, Value);
        }


    }

三、不同类型文件操作接口实现

1.INI文件

代码如下:

    class INIHalper : IFileBase
    {

        #region **************INIFileHelper****************

        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);


        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string defVal, Byte[] retVal, int size, string filePath);
        
        /// <summary>
        /// 写INI文件
        /// </summary>
        /// <param name="Section"></param>
        /// <param name="Key"></param>
        /// <param name="Value"></param>
        public void IniWriteValue(string path, string Section, string Key, string Value)
        {
            WritePrivateProfileString(Section, Key, Value, path);
        }

        /// <summary>
        /// 读取INI文件
        /// </summary>
        /// <param name="Section">INI文件中的一个字段名</param>
        /// <param name="Key">键名</param>
        /// <returns></returns>
        public string IniReadValue(string path,string Section, string Key)
        {
            StringBuilder temp = new StringBuilder(255);
            int i = GetPrivateProfileString(Section, Key, "", temp, 255, path);
            return temp.ToString();
        }

        public byte[] IniReadValues(string path,string section, string key)
        {
            byte[] temp = new byte[255];
            int i = GetPrivateProfileString(section, key, "", temp, 255, path);
            return temp;

        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <returns></returns>
        T Deserialize<T>(ref T Value,string path)
        {
            Type tInfo = Value.GetType();
            string section = tInfo.Name;
            foreach (PropertyInfo p in tInfo.GetProperties())
            {
                string key = p.Name;
                string iniValue = IniReadValue(path, section, key);
                if (iniValue == string.Empty)
                {
                    PropertyInfo pd = Value.GetType().GetProperty(key);
                    iniValue = pd.GetValue(Value, null) as string;
                }
                //string v = p.PropertyType == null ? "" : p.PropertyType.ToString();
                //object value = iniValue.Format(p.PropertyType);
                object value = Convert.ChangeType(iniValue, p.PropertyType);
                p.SetValue(Value, value, null);
            }
            return Value;
        }

        /// <summary>
        /// 序列化保存
        /// </summary>
        /// <returns></returns>
        public bool Serialize<T>(T Value, string path)
        {
            Type tInfo = Value.GetType();
            string section = tInfo.Name;
            foreach (PropertyInfo p in tInfo.GetProperties())
            {
                string key = p.Name;
                object value = p.GetValue(Value, null);
                string v = value == null ? "" : value.ToString();

                IniWriteValue(path,section, key, v);
            }
            return true;
        }



        /// <summary>
        /// 删除ini文件下所有段落
        /// </summary>
        public void ClearAllSection(string path)
        {
            IniWriteValue (path,null, null, null);
        }

        /// <summary>
        /// 删除ini文件下personal段落下的所有键
        /// </summary>
        /// <param name="Section"></param>
        public void ClearSection(string path,string Section)
        {
            IniWriteValue(path,Section, null, null);
        }
        #endregion

        public short ReadINI(string tablename, string id, string Key ,ref string value)
        {
            short ret = 0;
            try
            {
                value = IniReadValue(tablename, id, Key);
            }
            catch (Exception ex)
            {
                ret = -1;
            }

            return ret;

        }

        public short WriteINI(string path, string Section, string Key, string Value)
        {

            short ret = 0;
            try
            {
                IniWriteValue( path,  Section,  Key,  Value);
            }
            catch (Exception ex)
            {

                ret = -1;
            }

            return ret;
        }

        public short Read<T>(string tablename, ref T Value)
        {
            short ret = 0;

            try
            {
                Deserialize<T>(ref Value, tablename);
            }
            catch (Exception ex)
            {

                ret = -1;
            }
            return ret;
        }

        short FileBase.Write<T>(string tableName, string id, T data)
        {
            short ret = 0;
            try
            {
                Serialize<T>(data, tableName);
            }
            catch (Exception ex)
            {
                ret = -1;
            }
            return ret;

        }
    }

2.XML文件

代码如下:

  class XMLHalper : IFileBase
    {        

        #region ***************XMLFileHelper***************

        /// <summary>
        /// 文件化XML序列化
        /// </summary>
        /// <param name="obj">对象</param>
        /// <param name="filename">文件路径</param>
        public static bool Save(object obj, string filename)
        {
            bool ret = false;
            FileStream fs = null;
            try
            {
                fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
                XmlSerializer serializer = new XmlSerializer(obj.GetType());
                serializer.Serialize(fs, obj);
                ret = true;
            }
            catch (Exception ex)
            {
                ret = false;
                throw ex;
            }
            finally
            {
                if (fs != null) fs.Close();
            }

            return ret;
        }

        /// <summary>
        /// 文件化XML反序列化
        /// </summary>
        /// <param name="type">对象类型</param>
        /// <param name="filename">文件路径</param>
        public static object Load(Type type, string filename=null)
        {
            FileStream fs = null;
            try
            {
                fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                XmlSerializer serializer = new XmlSerializer(type);
                return serializer.Deserialize(fs);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (fs != null) fs.Close();
            }
        }

        #endregion

        public short Write<T>(string tableName, string id, T data)
        {
            short ret = 0;

            try
            {
                if (!Save(data, tableName))
                {
                    ret = -1;
                } 
            }
            catch (Exception ex)
            {
                ret = -1;
            }
            return ret;
        }

        public short Read<T>(string tablename, ref T Value)
        {
            short ret = 0;
            try
            {

                object o = Load(Value.GetType(), tablename);
                Value = (T)Convert.ChangeType(o, Value.GetType());
            }
            catch (Exception ex)
            {
                ret = -1;
            }
            return ret;
        }



        public short WriteINI(string path, string Section, string Key, string Value)
        {
            throw new NotImplementedException();
        }

        public short ReadINI(string tablename, string id, string Key, ref string data)
        {
            throw new NotImplementedException();
        }
    }

2.Json文件

代码如下:

class JsonHalper : IFileBase
{

    public short Save<T>(string path, T data)
    {
        short ret = 0;
        try
        {
            var jsonSetting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
            //Json.NET序列化
            string jsonData = JsonConvert.SerializeObject(data, Newtonsoft.Json.Formatting.Indented, jsonSetting);
            //保存数据
            File.WriteAllText(path, jsonData);
        }
        catch (Exception ex)
        {

            ret = -1;
        }
        return ret;
    }

    public short Load<T>(string path,ref T data)
    {
        short ret = 0;
        try
        {                
            //读取数据
            string jsonsting = File.ReadAllText(path);
            //反序列化
            data = JsonConvert.DeserializeObject<T>(jsonsting);//反序列化
        }
        catch (Exception ex)
        {
            ret = -1; 
        }
        return ret;
    }

    public short Load<T>(string path, ref List<T> data)
    {
        short ret = 0;
        try
        {
            //读取数据
            string jsonsting = File.ReadAllText(path);
            //反序列化
            data = JsonConvert.DeserializeObject<List<T>>(jsonsting);//反序列化
        }
        catch (Exception ex)
        {
            ret = -1;
        }
        return ret;
    }

    public short Read<T>(string tablename, ref T Value)
    {
        return Load<T>(tablename, ref Value);
    }

    public short Write<T>(string tableName, string id, T data)
    {
       return  Save<T>(tableName,data);
    }

    public short ReadINI(string tablename, string id, string Key, ref string data)
    {
        throw new NotImplementedException();
    }


    public short WriteINI(string path, string Section, string Key, string Value)
    {
        throw new NotImplementedException();
    }
}

总结

这样做是为了方便直接将类转存至文件,以及文件转换出类型,不足是部分数据类型如字典,不支持XML,INI直接序列化 需要自己做处理。

这样做添加新的文件操作类型时需要在添加修改

 public FileHelper(FileType fileType)
        {
            type = fileType;
            switch (fileType)
            {
                case FileType.INIFile:
                    file = new INIHalper();
                    break;
                case FileType.XMLFile:
                    file = new XMLHalper();
                    break;

                case FileType.JSONFile:
                    file = new JsonHalper();
                    break;

                default:
                    break;
            }
        }

可以换为构造函数直接传参的方式

public FileHelper(IFileBase fileType)
{
		file =fileType;
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值