I’m writing a program that iterates a file tree and now I need it to write the results to a csv file. It’s required that the contents be sorted alphanumerically before being written to the csv file. So I have been saving the files to a List.
FileInfo fi = new FileInfo(file);
fileList.Add( new Record {
fileName = fi.Name,
fileSize = fi.Length
});
Where Record is a class:
public class Record
{
public long fileSize { get; set; }
public string fileName { get; set; }
}
Then I’m doing a plain old Sort(). Now how can I write this list to a csv?
I welcome any better ways to do the whole process.
Is there a way that I can write the results to the csv as I go and then sort the csv alphanumerically? Basically the program has to sort it and not the user.
The csv also needs headers if you could get me going on that as well.
You can use LINQ for the sorting and a
StreamWriterfor the file creation.Note that I enclosed the file name in double quotes (“), in the case that a comma (,) is part of the file name. The double quote itself is not a valid character for file names in Windows, so that it should not be a problem.