简体   繁体   中英

How do I write a List<String> into a .csv file as a single column?

Right now I have a simple application where I have a C# object that has a List<String> as part of its attributes. It is supposed to store a list of strings alongside the other attributes and output it as a .csv file with headers.

After creating the object and outputting it as a .csv file, the column containing the list is not in the output and I don't know how to exactly handle it or converting it to a .csv format.

My intended output is:

Name,ID,Date,Number,FilePaths,Remarks
Value1, Value2, Value3, Value 4,List here,Value6

The output .csv file will then be serialized into JSON and be deserialized in another component where it is going to read the values and eventually be put into a database.

The class (POCO):

class Object 
{
   public string Name { get; set; }
   public string ID { get; set; }
   public DateTime Date { get; set; }
   public long Number { get; set; }
   public List<String> FilePaths { get; set; }
   public string Messages {get; set; }
}

And here is how I instantiate the object from the data collected from inputs:

List<String> paths = new List<String>();

foreach(var file in files)
{
   paths.Add(file.FullName);
}

List<Object> newObject = new List<Object> {
new Object { Name = value1, ID = value2, Date = value3, Number = value4, FilePaths = paths, Messages = value6 };

using(var writer = new CsvWriter(outputStream))
{
   writer.WriteRecords(newObject);
}

However the output seems to be:

Name,ID,Date,Number,Remarks
value1,value2,value3,value4,value6

It seems to have skipped the list.

EDIT:

To elaborate further, the FilePaths are actually a list of strings that contain the directory paths of files the user has uploaded to the program. What I plan to do is to have the list of file paths retrieved from List<FileInfo> files by calling a for loop and storing their paths into an organized fashion. This is because one user has the ability to upload multiple files as according to the requirements.

Declare FilePaths as string. Convert List as the string you want and And then write to csv file.

Try initializing your list of object as the following:

List<Object> newObject = new List<Object> {
            new Object {
                  Name = value1,
                  ID = value2,
                  Date = value3,
                  Number = value4,
                  FilePaths = paths.Any() ? $"\"{string.Join(",", paths.ToList())}\"" : null;,
                  Messages = value6
            }
      };

CsvHelper skips over Enumerable properties unless you give it more information on how it should handle them. This would be one way to output your CSV file by separating each FilePath value with a comma.

public static void Main(string[] args)
{
    var paths = new List<string> { "path1", "path2", "path3" };

    List<Object> newObject = new List<Object> {
        new Object
        {
            Name = "NameValue",
            ID = "IdValue",
            Date = DateTime.Now,
            Number = 12345,
            FilePaths = paths,
            Messages = "MessagesValue"
        }
    };

    using (var csv = new CsvWriter(outputStream))
    {
        csv.Configuration.RegisterClassMap(new ObjectMap());
        csv.WriteRecords(newObject);
    }
}

public class ObjectMap : ClassMap<Object>
{
    public ObjectMap()
    {
        AutoMap();
        Map(m => m.FilePaths).TypeConverter<ListStringConverter>();
    }
}

private class ListStringConverter : StringConverter
{
    public override string ConvertToString(object value, IWriterRow row, MemberMapData memberMapData)
    {
        var returnValue = string.Empty;

        var list = (List<string>)value;

        if (list != null)
        {
            returnValue = string.Join(",", list);
        }        

        return base.ConvertToString(returnValue, row, memberMapData);
    }

    public override object ConvertFromString(string text, IReaderRow row, MemberMapData memberMapData)
    {
        var list = text.Split(',').ToList();

        return list;
    }
}

public class Object
{
    public string Name { get; set; }
    public string ID { get; set; }
    public DateTime Date { get; set; }
    public long Number { get; set; }
    public List<String> FilePaths { get; set; }
    public string Messages { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM