使用 FileHelpers 从 asp.net 文件上传读取 CSV 文件

Mos*_*hua 3 c# asp.net filehelpers dotnetnuke

我正在开发 ASP.NET Webforms C# 应用程序。我需要将 CSV 文件上传到服务器,并将内容读取并保存到数据库。我在某处读到FileHelpers可用于读取 csv 文件,但我还没有看到任何处理 HttpPostedFile 的示例。有人有使用 filehelpers 进行文件上传的经验吗?

我也愿意接受替代方法。谢谢。

nun*_*cal 6

这是一个帮助您入门的示例。

using FileHelpers;

// First declare the record class

[Delimitedrecord("|")]
public class SampleType
{
    public string Field1;
    public int    Field2;
}


public void ReadExample(HttpPostedFile file)
{
    FileHelperEngine engine = new FileHelperEngine(typeof(SampleType));

    SampleType[] records;    

    records = (SampleType[]) engine.ReadStream(
                         new StreamReader(file.InputStream), Int32.MaxValue);

    // Now "records" array contains all the records in the
    // uploaded file and can be acceded like this:

    int sum = records[0].Field2 + records[1].Field2;
}
Run Code Online (Sandbox Code Playgroud)