如何在不将其保存到服务器的情况下读取上传的CSV文件?

时间:2012-12-13 15:19:35

标签: c# csv

大家好,我有这种格式的CSV文件:

**CSV Format1**

  ||OrderGUID||OrderItemID||Qty||SKUID||TrackingNumber||TotalWeight||DateShipped||DateDelivered||ShippingStatusId||OrderShippingAddressId
  ||5        ||3          ||2  ||12312||aasdasd       ||24         ||2012-12-2010||            || 10025          ||10028
  ||5        ||4          ||3  ||113123||adadasdasd   ||22         ||2012-12-2012||            ||10026           ||10028



**CSV Format2**

    ||"OrderGUID"||"OrderItemID"||"Qty"||"SKUID"||"TrackingNumber"||"TotalWeight"||"DateShipped"||"DateDelivered"||"ShippingStatusId"||"OrderShippingAddressId"||
    ||"5"        ||"3"          ||"2"  ||"12312"||"aasdasd"       ||"24"         ||"2012-12-2010"||""            || "10025"          ||"10028"||
    ||"5"        ||"4"          ||"3"  ||"113123"||"adadasdasd"   ||"22"         ||"2012-12-2012"|| "2012-12-2010" ||"10026"           ||"10028"||

我必须阅读这些文件而不将它们保存在服务器上。谁能帮我?如何读取此文件并插入我的数据库?如何修剪文件中的特殊字符?

这就是我要为文件上传做的事情:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ImportTrackingNumber(FormCollection form,HttpPostedFileBase UploadedFile,TrackingNumbersModel Trackingnumbers)
{
    if (UploadedFile != null)
    {
        var allowedExtensions = new[] {".xlsx", ".csv"};
        if (UploadedFile.ContentLength > 0)
        {                   
            var extension = Path.GetExtension(UploadedFile.FileName);
            if (extension == ".xlsx")
            {
                //Need To code For Excel Files Reading
            }
            else if (extension == ".csv")
            {
                //string filename = Path.GetFileName(UploadedFile.PostedFile.InputStream);
                StreamReader csvreader = new StreamReader(UploadedFile.FileName);
                DataTable dt;        
            }
        }
    }
    return View();
}

2 个答案:

答案 0 :(得分:39)

仅举例说明如何在不将其保存在服务器上的情况下阅读上传的文件:

// Use the InputStream to get the actual stream sent.
StreamReader csvreader = new StreamReader(UploadedFile.InputStream);

while (!csvreader.EndOfStream)
{
    var line = csvreader.ReadLine();
    var values = line.Split(';');
}

答案 1 :(得分:0)

这是我的代码:

public static DataTable GetDataTabletFromCSVFile(HttpPostedFileBase file)
{
    DataTable csvDataTable = new DataTable();

    // Read bytes from http input stream
    var csvBody = string.Empty;

    using (BinaryReader b = new BinaryReader(file.InputStream))
    {
        byte[] binData = b.ReadBytes(file.ContentLength);
        csvBody = Encoding.UTF8.GetString(binData);
    }

    var memoryStream = new MemoryStream();
    var streamWriter = new StreamWriter(memoryStream);
    streamWriter.Write(csvBody);
    streamWriter.Flush();
    memoryStream.Position = 0;

    using (TextFieldParser csvReader = new TextFieldParser(memoryStream))
    {
        csvReader.SetDelimiters(new string[] { "," });
        csvReader.HasFieldsEnclosedInQuotes = true;
        string[] colFields = csvReader.ReadFields();
        foreach (string column in colFields)
        {
            DataColumn datecolumn = new DataColumn(column);
            datecolumn.AllowDBNull = true;
            csvDataTable.Columns.Add(datecolumn);
        }
        while (!csvReader.EndOfData)
        {
            string[] fieldData = csvReader.ReadFields();
            //Making empty value as null
            for (int i = 0; i < fieldData.Length; i++)
            {
                if (fieldData[i] == "")
                {
                    fieldData[i] = null;
                }
            }

            csvDataTable.Rows.Add(fieldData);
        }
    }

    return csvDataTable;
}