Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 对于csv转换列表<;类别>;转换为字节数组_C#_Asp.net Mvc 3_List_Csv - Fatal编程技术网

C# 对于csv转换列表<;类别>;转换为字节数组

C# 对于csv转换列表<;类别>;转换为字节数组,c#,asp.net-mvc-3,list,csv,C#,Asp.net Mvc 3,List,Csv,我有一个行动 public FileContentResult DownloadCSV() { var people = new List<Person> { new Person("Matt", "Abbott"), new Person("John","Smith") }; string csv = "Charlie, Chaplin, Chuckles"; Extensions.ToCSV(new DataTable()

我有一个行动

 public FileContentResult DownloadCSV()
    {
        var people = new List<Person> { new Person("Matt", "Abbott"), new Person("John","Smith") };
        string csv = "Charlie, Chaplin, Chuckles";
        Extensions.ToCSV(new DataTable());
        return File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv", "Report123.csv");
    }
如何转换成字节数组

var people = new List<Person> { new Person("Matt", "Abbott"), new Person("John","Smith") };
var people=newlist{新人(“马特”、“雅培”)、新人(“约翰”、“史密斯”)};

进入带有csv格式头的字节数组

我不明白您想要什么。但根据我对您前面提出的问题的理解,以下是将对象转换为字节[]的方法

static void Main(string[] args)
{
  Person p1 = new Person();
  p1.ID = 1;
  p1.Name = "Test";

  byte[] bytes = ObjectToByteArray(p1);
}

private byte[] ObjectToByteArray(Object obj) 
{ 
  if(obj == null) 
    return null; 
  BinaryFormatter bf = new BinaryFormatter(); 
  MemoryStream ms = new MemoryStream(); 
  bf.Serialize(ms, obj); 
  return ms.ToArray(); 
}


[Serializable]
public class Person
{
  public int ID { get; set; }
  public string Name { get; set; }
}

考虑到您没有显示成员
Person
拥有什么,这有点不可能。。。也;CSV是非常重要的,如果我们包括转义值、多行值等,那么我们就不清楚您在问什么。您是否只是想循环查看
人员
,并构建一个字符串以存储在CSV中?你想在这个字符串中得到什么?我想要一种将csv中的列表值转换为格式化的waybf.Serialize(ms,obj)的方法;显示错误“未标记为可序列化”。您需要在类中添加[serializable]属性以启用序列化。
var people = new List<Person> { new Person("Matt", "Abbott"), new Person("John","Smith") };
static void Main(string[] args)
{
  Person p1 = new Person();
  p1.ID = 1;
  p1.Name = "Test";

  byte[] bytes = ObjectToByteArray(p1);
}

private byte[] ObjectToByteArray(Object obj) 
{ 
  if(obj == null) 
    return null; 
  BinaryFormatter bf = new BinaryFormatter(); 
  MemoryStream ms = new MemoryStream(); 
  bf.Serialize(ms, obj); 
  return ms.ToArray(); 
}


[Serializable]
public class Person
{
  public int ID { get; set; }
  public string Name { get; set; }
}