C# 读取公共类属性保存为csv

            Publicfile publicfile = new Publicfile();
            publicfile.FileName = "TESTFILE";
            publicfile.Position1 = 100;

            Type type = typeof(Publicfile);
            PropertyInfo[] props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
       //方法一
            StringBuilder outputText = new StringBuilder();
            outputText.AppendLine(string.Join(",", props.Select(p => $"{p.Name}_")));
            outputText.AppendLine(string.Join(",", props.Select(p => p.GetValue(publicfile)?.ToString() ?? string.Empty)));
            File.WriteAllText(@"C:\Users\TEST\XXX1.csv", outputText.ToString());
        //方法二
            FileStream fs = new FileStream(@"C:\Users\TEST\XXX2.csv", FileMode.Create, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.ASCII);
            sw.WriteLine(string.Join(",", props.Select(p => p.Name)));
            sw.WriteLine(string.Join(",", props.Select(p => p.GetValue(publicofile)?.ToString() ?? string.Empty)));
            sw.Close();
            fs.Close();

 

posted @ 2024-12-18 14:36  芈璐  阅读(7)  评论(0编辑  收藏  举报