我正在尝试将数据表的内容发送到带有标头的csv文件。有一个重复的问题,但接受的答案似乎只有一半的工作。在这一点上,我已经混合并匹配得到的赞成,没有运气,需要一个正确的方向。
我可以把列写到文件中,我可以写好数据但不能一起编写。此外,数据永远不会引用,只有逗号分隔,不带引号。
//This is how the FileHelpers class is built
public class ScannedFileInfo
{
//this prefix will handle the double quotes issue
//delimiters must reside between double quotes
//Must specify FieldOrder too
[FieldQuoted('"', QuoteMode.AlwaysQuoted)]
[FieldOrder(1)]
public string DA_Id;
[FieldQuoted('"', QuoteMode.AlwaysQuoted)]
[FieldOrder(2)]
public string Name;
[FieldQuoted('"', QuoteMode.AlwaysQuoted)]
[FieldOrder(3)]
public string Extension;
[FieldQuoted('"', QuoteMode.AlwaysQuoted)]
[FieldOrder(4)]
public string Fullname;
[FieldQuoted('"', QuoteMode.AlwaysQuoted)]
[FieldOrder(5)]
public string PathLength;
[FieldQuoted('"', QuoteMode.OptionalForBoth)]
[FieldOrder(6)]
public string Directory;
}
//this is how I send it to the file
public static void ImportDirectory(string result, SqlConnection myconn, SqlConnection destConn ,ListBox lbInfo, DataGridView dgView)
{
//create data table code here - works fine...
MessageBox.Show("Scan complete. Starting Import...");
//build file
var engine = new FileHelperEngine<ScannedFileInfo>();
var orders = new List<ScannedFileInfo>();
engine.HeaderText = engine.GetFileHeader();
engine.WriteFile(@"C:\DirectoryScan.csv", orders);
MessageBox.Show("You now have proper labeled columns in your file.");
//now the data import is successful but it overwrites the column info
CommonEngine.DataTableToCsv(dt, @"C:\DirectoryScan.csv", ',');
MessageBox.Show("You now have data in your file, but no columns");
}
答案 0 :(得分:1)
FileHelpersEngine
电话不支持CommonEngine
的所有功能。特别是,缺少字段引用和列标题。 FileHelpersEngine<T>
的功能不如ScannedFileInfo
。
相反,您应该创建一个FileHelpersEngine<ScannedFileInfo>.WriteFile()
而不是数据表的列表,然后使用//create list of ScannedFileInfo here
var records = new List<ScannedFileInfo>();
records.Add(new ScannedFileInfo() { Name = ..., etc... });
// ( or if you prefer, loop through your datatable to build the list)
MessageBox.Show("Scan complete. Starting Import...");
// build file
var engine = new FileHelperEngine<ScannedFileInfo>();
engine.HeaderText = engine.GetFileHeader();
engine.WriteFile(@"C:\DirectoryScan.csv", records);
MessageBox.Show("You now have data and properly labelled columns in your file.");
。
{{1}}
答案 1 :(得分:0)
我不建议您充分研究CSVHelper。这个nuget包让我免于在很多场合拔头发,我无法统计它们。
如果您正在使用它,您可以使用配置设置快速设置标题记录,分隔符,忽略引号或等等。