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

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Reflection;
using System.Text;
using System.Linq;

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

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 (GetAttributes<FileSaveAttribute>(key, out object isSave))
            {
                if (!(bool)isSave)
                {
                    continue;
                }
            }
            //不存在默认为保存
            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);
    }

    /// <summary>
    /// 获取该属性设对应的特性值(若该属性没有这个特性会抛出异常)
    /// </summary>
    bool GetAttributes<A>(string propertyName, out object value)
    {
        value = default;
        Type attributeType = typeof(A);
        PropertyInfo propertyInfo = typeof(T).GetProperties().FirstOrDefault(p => p.Name == propertyName);
        if (propertyInfo != null)
        {
            Attribute attr = Attribute.GetCustomAttribute(propertyInfo, attributeType);
            if (attr != null)
            {
                string attributeFieldName = string.Empty;
                switch (attributeType.Name)
                {
                    case "CategoryAttribute": attributeFieldName = "categoryValue"; break;
                    case "DescriptionAttribute": attributeFieldName = "description"; break;
                    case "DisplayNameAttribute": attributeFieldName = "_displayName"; break;
                    case "ReadOnlyAttribute": attributeFieldName = "isReadOnly"; break;
                    case "BrowsableAttribute": attributeFieldName = "browsable"; break;
                    case "DefaultValueAttribute": attributeFieldName = "value"; break;
                    case "FileSaveAttribute": attributeFieldName = "Save"; break;
                    default:
                        return false;
                }
                PropertyDescriptorCollection attributes = TypeDescriptor.GetProperties(typeof(T));
                FieldInfo fieldInfo = attributeType.GetField(attributeFieldName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.CreateInstance);
                value = fieldInfo.GetValue(attributes[propertyInfo.Name].Attributes[attributeType]);
                return true;
            }
        }
        return false;
    }

}

posted @ 2022-04-12 22:45  Bridgebug  阅读(1209)  评论(0编辑  收藏  举报