C#csv文件保存(通用版)

    /// <summary>
    /// 指定是否保存到文件中
    /// </summary>
    [AttributeUsage(AttributeTargets.Property)]
    public sealed class FileSaveAttribute : Attribute
    {
        public bool Save { get; set; }
        public FileSaveAttribute(bool isSave)
        {
            Save = isSave;
        }
    }

    /// <summary>
    /// 指定属性的格式化格式
    /// </summary>
    [AttributeUsage(AttributeTargets.Property)]
    public sealed class FormatAttribute : Attribute
    {
        public string Format { get; set; }
        public FormatAttribute(string format)
        {
            Format = format;
        }
    }

    public class FileSave<T>
    {
        public void CsvSave(string path, List<T> list, string title = null)
        {
            StringBuilder sb = new StringBuilder();
            if (title != null)
            {
                sb.AppendLine(title);
            }
            Type tInfo = typeof(T);
            List<object> listHeader = new List<object>();
            Dictionary<string, object> dictData = new Dictionary<string, object>();
            foreach (PropertyInfo p in tInfo.GetProperties())
            {
                string key = p.Name;
                if (tInfo.GetAttributes<FileSaveAttribute>(key, out object isSave))
                {
                    if (!(bool)isSave)
                    {
                        continue;
                    }
                }
                //不存在默认为保存
                tInfo.GetAttributes<DisplayNameAttribute>(key, out object displayName);
                listHeader.Add(displayName ?? key);
                dictData[key] = null;
            }
            sb.AppendLine(string.Join(",", listHeader));
            foreach (var model in list)
            {
                foreach (PropertyInfo p in tInfo.GetProperties())
                {
                    string key = p.Name;
                    if (dictData.ContainsKey(key))
                    {
                        dictData[key] = p.GetValue(model, null);
                    }
                }
                sb.AppendLine(string.Join(",", dictData.Values));
            }
            File.WriteAllText(path, sb.ToString(), Encoding.Default);
        }

    }

    public static class ExtentionMethod
    {
        /// <summary>
        /// 获取该类型中的属性有没有对应的特性值
        /// </summary>
        /// <typeparam name="T">特性类型</typeparam>
        /// <param name="type">查找的class类型</param>
        /// <param name="propertyName">class中的属性名称</param>
        /// <param name="value">out:特性值</param>
        /// <returns>是否存在该特性</returns>
        public static bool GetAttributes<T>(this Type type, string propertyName, out object value) where T : Attribute
        {
            value = default;
            Type attributeType = typeof(T);
            PropertyInfo propertyInfo = type.GetProperties().FirstOrDefault(p => p.Name == propertyName);
            if (propertyInfo != null)
            {
                Attribute attr = Attribute.GetCustomAttribute(propertyInfo, attributeType);
                if (attr != null)
                {
                    string attrPropertyName = string.Empty;
                    switch (attributeType.Name)
                    {
                        case "CategoryAttribute": attrPropertyName = "Category"; break;
                        case "DescriptionAttribute": attrPropertyName = "Description"; break;
                        case "DisplayNameAttribute": attrPropertyName = "DisplayName"; break;
                        case "ReadOnlyAttribute": attrPropertyName = "IsReadOnly"; break;
                        case "BrowsableAttribute": attrPropertyName = "Browsable"; break;
                        case "DefaultValueAttribute": attrPropertyName = "Value"; break;
                        case "FileSaveAttribute": attrPropertyName = "Save"; break;
                        case "FormatAttribute": attrPropertyName = "Format"; break;
                        default:
                            return false;
                    }
                    PropertyDescriptorCollection attrPropertys = TypeDescriptor.GetProperties(type);
                    var fs = attributeType.GetProperties();
                    PropertyInfo attrPropertyInfo = attributeType.GetProperty(attrPropertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance);
                    value = attrPropertyInfo.GetValue(attrPropertys[propertyInfo.Name].Attributes[attributeType]);
                    return true;
                }
            }
            return false;
        }
    }


版权声明:本文为breakbridge原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。