当前位置: 首页>>代码示例>>C#>>正文


C# CsvReader.GetRecords方法代码示例

本文整理汇总了C#中CsvReader.GetRecords方法的典型用法代码示例。如果您正苦于以下问题:C# CsvReader.GetRecords方法的具体用法?C# CsvReader.GetRecords怎么用?C# CsvReader.GetRecords使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在CsvReader的用法示例。


在下文中一共展示了CsvReader.GetRecords方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: SecurityControllerTest

        public void SecurityControllerTest()
        {
            //http://www.davepaquette.com/archive/2014/03/18/seeding-entity-framework-database-from-csv.aspx
            //http://adrianmejia.com/blog/2011/07/18/cs-getmanifestresourcestream-gotcha
            Assembly assembly = Assembly.GetExecutingAssembly();
            string resourceName = "ShareWealth.Web.Test.SeedData.stockPrice.csv";
            ApplicationDbContext context = new ApplicationDbContext();

            using (Stream stream = assembly.GetManifestResourceStream(resourceName))
            {
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    CsvReader csvReader = new CsvReader(reader);
                    csvReader.Configuration.WillThrowOnMissingField = false;
                    var stockPrice = csvReader.GetRecords<StockPrice>().ToArray();
                    for (int i = 1; i < 4 ; i++)
                    {
                        var sp = new StockPrice {
                           Id = i,
                           TradingDate = new DateTime(2013,12,5),
                           SecurityId = stockPrice[i].SecurityId,
                           Open = stockPrice[i].Open,
                           High = stockPrice[i].High,
                           Low = stockPrice[i].Low,
                           Close = stockPrice[i].Close,
                        };
                        context.StockPrices.Add(sp);

                    }
                    context.SaveChanges();

                }
            }
        }
开发者ID:alcjamgit,项目名称:zulu2,代码行数:34,代码来源:SecurityControllerTests.cs

示例2: AddUpdateDeleteInventories

        private static void AddUpdateDeleteInventories(ZipArchiveEntry inventoriesEntry)
        {
            Console.WriteLine("inventories.csv is {0} bytes", inventoriesEntry.Length);
            IEnumerable<Inventory> inventories = null;

            using (var entryStream = inventoriesEntry.Open())
            {
                Console.WriteLine("Starting inventories at {0:hh:mm:ss.fff}", DateTime.Now);
                var stopwatch = new Stopwatch();
                stopwatch.Start();

                var reader = new StreamReader(entryStream);
                var csv = new CsvReader(reader);
                csv.Configuration.RegisterClassMap(new InventoryMap());
                StringBuilder invForImport = new StringBuilder();
                inventories = csv.GetRecords<Inventory>().Where(i => !i.IsDead);

                var inventoryCollection = new InventoryCollection();
                inventoryCollection.SetItems(inventories);
                var importer = new NpgsqlBulkImporter(ConfigurationManager.ConnectionStrings["spurious"].ConnectionString, stopwatch);
                importer.BulkImport("inventories", inventoryCollection);

                stopwatch.Stop();
                Console.WriteLine("Finished inventories at {0:hh:mm:ss.fff}, taking {1}", DateTime.Now, stopwatch.Elapsed);
            }
        }
开发者ID:claq2,项目名称:Spurious,代码行数:26,代码来源:Program.cs

示例3: GetJobDetailsAsync

        public async Task<List<JobDetails>> GetJobDetailsAsync(string pipelineName, string stageName, string jobName)
        {
            try
            {
                    var searchUrl = Urls.SearchUrl;
                    var query = new NameValueCollection {
                                                   {nameof(searchUrl), searchUrl},
                                                   {nameof(pipelineName), pipelineName},
                                                   {nameof(stageName), stageName},
                                                   {nameof(jobName), jobName},
                                                   {@"limitCount", jobLimitCount.ToString()},
                                                   {@"limitPipeline", "latest"}
                                              };

                    var uri = new Uri(searchUrl).AttachParameters(query);
                    var stream = await Dispatch.GetRawStreamAsync(uri);
                    using (var reader = new StreamReader(stream))
                    {
                        using (var csvReader = new CsvReader(reader))
                        {
                            var records = csvReader.GetRecords<JobDetails>();
                            return records.ToList();
                        }
                    }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return Enumerable.Empty<JobDetails>().ToList();
            }
        }
开发者ID:ashutoshraina,项目名称:Jalebi,代码行数:31,代码来源:Timing.cs

示例4: Index

        public ActionResult Index(HttpPostedFileBase file)
        {
            if (file.ContentLength > 0)
            {
                var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
                if (System.IO.File.Exists(path))
                    System.IO.File.Delete(path);
                file.SaveAs(path);
                //Stream reader will read test.csv file in current folder
                StreamReader sr = new StreamReader(path);
                //Csv reader reads the stream
                CsvReader csvread = new CsvReader(sr);

                //csvread will fetch all record in one go to the IEnumerable object record
                IEnumerable<MenuItem> records = csvread.GetRecords<MenuItem>();
                context.Database.ExecuteSqlCommand("delete from Menus");
                context.SaveChanges();
                foreach (MenuItem item in records)
                {
                    Menu m = new Menu();
                    m.Name = item.Name;
                    m.DayOfWeek = item.DayOfWeek;
                    m.Price = item.Price;
                    context.Menus.Add(m);
                    context.SaveChanges();
                }
                sr.Close();
                ViewBag.ImportSuccess = "Import CSV file successfully!";
            }

            return View();
        }
开发者ID:valendo,项目名称:Order,代码行数:33,代码来源:CsvController.cs

示例5: Blah

        public void Blah()
        {
            using( var stream = new MemoryStream() )
            using( var reader = new StreamReader( stream ) )
            using( var writer = new StreamWriter( stream ) )
            using( var csv = new CsvReader( reader ) )
            {
                writer.WriteLine( "Id,Name" );
                writer.WriteLine( "1,one" );
                writer.Flush();
                stream.Position = 0;

                var records = csv.GetRecords<Test>().ToList();

                var position = stream.Position;
                writer.WriteLine( "2,two" );
                writer.Flush();
                stream.Position = position;

                records = csv.GetRecords<Test>().ToList();

                writer.WriteLine( "2,two" );
                writer.Flush();
                stream.Position = position;

                Assert.AreEqual( 1, records.Count );
                Assert.AreEqual( 2, records[0].Id );
                Assert.AreEqual( "two", records[0].Name );
            }
        }
开发者ID:ravensorb,项目名称:CsvHelper,代码行数:30,代码来源:MultipleGetRecordsTests.cs

示例6: readcsv_Click

        void readcsv_Click(object sender, RoutedEventArgs e)
        {
            using (var sr = new StreamReader(@"restaurant.csv"))
            {
                var reader = new CsvReader(sr);
                List<restaurant> LISTrecord = new List<restaurant>();

                //CSVReader will now read the whole file into an enumerable
                IEnumerable<restaurant> records = reader.GetRecords<restaurant>();

                int n = 2;
                
                var query =
                    from record in records
                    where record.Trial == n
                    select record;

                //Print Result of Query
                foreach (var g in query.Take(5))
                {
                    //Debug.Print("Name: {0}, Rating: {1}", g.Name, g.Rating);
                    LISTrecord.Add(g);
                }

                Debug.Print(LISTrecord[1].Name);

            }
        }
开发者ID:chunc,项目名称:VCS-Bridge-Study,代码行数:28,代码来源:demo1.xaml.cs

示例7: LoadFlightsAsync

        private static async Task LoadFlightsAsync(string csvFilename)
        {
            Console.WriteLine("Loading {0}", Path.GetFileName(csvFilename));

            var collection = __database.GetCollection<Flight>("flights");

            var batchSize = 1000;
            using (var csvReader = new CsvReader(new StreamReader(csvFilename)))
            {
                var flights = new List<Flight>();

                foreach (var flight  in csvReader.GetRecords<Flight>())
                {
                    PreprocessFlight(flight);
                    flights.Add(flight);

                    if (flights.Count == batchSize)
                    {
                        await collection.InsertManyAsync(flights);
                        flights.Clear();
                        Console.Write(".");
                    }
                }

                if (flights.Count > 0)
                {
                    await collection.InsertManyAsync(flights);
                }
            }

            Console.WriteLine();
        }
开发者ID:jango2015,项目名称:SampleMongoDBApplication,代码行数:32,代码来源:Program.cs

示例8: Upload

        public ActionResult Upload(HttpPostedFileBase productFile)
        {
            string path = null;

            if (productFile.ContentLength > 0)
            {
                var filename = Path.GetFileName(productFile.FileName);
                path = AppDomain.CurrentDomain.BaseDirectory + "Upload\\" + filename;
                productFile.SaveAs(path);

                var csv = new CsvReader(new StreamReader(path));
                csv.Configuration.RegisterClassMap<ProductMap>();

                var productList = csv.GetRecords<Product>();

                foreach(var product in productList)
                {
                    product.Date = DateTime.Now;
                    db.Products.Add(product);
                }

                db.SaveChanges();
            }        
            return View();
        }
开发者ID:Pixelsltd,项目名称:eCommerce,代码行数:25,代码来源:AdminController.cs

示例9: LoadCsvFile

 private static void LoadCsvFile(Feed feed, KeyValuePair<string, Type> map, TextReader tr)
 {
     using (CsvReader reader = new CsvReader(tr))
     {
         SetFeed(feed, reader.GetRecords(map.Value).ToList(), map.Value);
     }
 }
开发者ID:patrickgreenwell,项目名称:GTFS,代码行数:7,代码来源:LoadHelper.cs

示例10: TestAll

        private static void TestAll(bool checkPadding)
        {
            using (var csvReader = new CsvReader(new StreamReader("Indicators/AtrTests.csv")))
            {
                var expectedRecords = csvReader.GetRecords<AtrDay>().ToList();

                if (checkPadding)
                {
                    var firstNonNullAtr = expectedRecords.First(r => r.Atr != null).Atr;
                    foreach (var r in expectedRecords.Where(r => r.Atr == null))
                        r.Atr = firstNonNullAtr;
                }

                var shareDays = expectedRecords
                    .Select(r => new ShareDay {Date = r.Date, High = r.High, Low = r.Low, Close = r.Close})
                    .ToArray();

                var parameters = new Atr.Parameters();
                var actualAtrCollection =
                    new Atr().Calculate(shareDays, parameters, 0, pad: checkPadding).ToList();

                var expectedAtrCollection =
                    expectedRecords.Where(r => r.Atr != null).Select(r => Point.With(r.Date, r.Atr.Value)).ToList();

                CollectionAssert.AreEqual(expectedAtrCollection, actualAtrCollection, new PointComparer(8));
            }
        }
开发者ID:singularity-zero,项目名称:SparkFire,代码行数:27,代码来源:AtrTests.cs

示例11: GetTransactionsFromCSV

        public List<Transaction> GetTransactionsFromCSV(string fullName)
        {
            var transactions = new List<Transaction>();
            using (var sr = new StreamReader(fullName))
            {
                var reader = new CsvReader(sr);
                reader.Parser.Configuration.HasHeaderRecord = false;
                reader.Parser.Configuration.IgnoreBlankLines = true;
                reader.Parser.Configuration.IgnoreHeaderWhiteSpace = true;
                reader.Parser.Configuration.Delimiter = ";";
                reader.Parser.Configuration.IgnoreReadingExceptions = true;

                var lines = reader.GetRecords<CSVLine>().ToList();
                foreach(var line in lines)
                {
                    var transaction = new Transaction()
                    {
                        Date = line.Date,
                        Category = line.Category,
                        SubCategory = line.SubCategory,
                        Name = line.Name,
                        Value = line.Value,
                    };

                    transactions.Add(transaction);
                }
            }

            return transactions;
        }
开发者ID:juniorgasparotto,项目名称:SpentBook,代码行数:30,代码来源:TransactionImportDefaultCSV.cs

示例12: Main

        private static void Main(string[] args)
        {
            var c = new CsvConfiguration()
                {
                    HasHeaderRecord = false
                };

            var csv = new CsvReader(new StreamReader(DbIpCityFile), c);

            var items = csv.GetRecords<DbIpCity>();
            var dt = DatabaseManager.GetDataTable();
            
            foreach (var item in items)
            {                
                var row = dt.NewRow();
                row["Ip_Start"] = item.IpStart;
                row["Ip_End"] = item.IpEnd;
                row["city"] = item.City;
                row["region"] = item.Region;
                row["country"] = item.Country;
                row["type"] = item.Type;
                dt.Rows.Add(row);
            }

            DatabaseManager.BulkInsert(ConnString, dt);
        }
开发者ID:JiangLongLiu,项目名称:ZORAN.DB.IP.Importer,代码行数:26,代码来源:Program.cs

示例13: ReadAll

 public IList<Offer> ReadAll(string fileName)
 {
     using (var reader = new CsvReader(File.OpenText(fileName)))
     {
         return reader.GetRecords<CsvRow>().Select(x => new Offer { Rate = x.Rate, CashAvailable = x.Available }).ToList();
     }
 }
开发者ID:skorunka,项目名称:ZopaTechnicalTestDeveloper,代码行数:7,代码来源:CsvReaderOffersReader.cs

示例14: Export

        public override int Export()
        {
            string SQL = BuildMemberInsertStatement();
            int assetCounter = 0;

            TextReader contents = new StringReader(File.ReadAllText(_config.RallySourceConnection.ExportFileDirectory + _config.RallySourceConnection.UserExportFilePrefix + ".csv"));
            var csv = new CsvReader(contents);
            var users = csv.GetRecords<MemberInfo>();

            foreach (MemberInfo member in users)
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = _sqlConn;
                    cmd.CommandText = SQL;
                    cmd.CommandType = System.Data.CommandType.Text;

                    cmd.Parameters.AddWithValue("@AssetOID", member.ObjectID.Trim());
                    cmd.Parameters.AddWithValue("@Username", member.UserName.Substring(0, member.UserName.IndexOf("@")));
                    cmd.Parameters.AddWithValue("@Password", member.UserName.Substring(0, member.UserName.IndexOf("@")));
                    cmd.Parameters.AddWithValue("@AssetState", GetMemberState(member.Disabled.ToUpper()));
                    cmd.Parameters.AddWithValue("@Email", member.UserName.Trim());
                    cmd.Parameters.AddWithValue("@Nickname", member.FirstName.Trim() + " " + member.LastName.Trim());
                    cmd.Parameters.AddWithValue("@Name", member.FirstName.Trim() + " " + member.LastName.Trim());
                    cmd.Parameters.AddWithValue("@Description", "Imported from Rally on " + DateTime.Now.ToShortDateString() + ".");
                    cmd.Parameters.AddWithValue("@DefaultRole", GetMemberDefaultRole(member.Permission.Trim()));
                    cmd.Parameters.AddWithValue("@NotifyViaEmail", "False");
                    cmd.Parameters.AddWithValue("@SendConversationEmails", "False");

                    cmd.ExecuteNonQuery();
                }
                assetCounter++;
            }
            return assetCounter;
        }
开发者ID:mtbadgley,项目名称:DisneyMigration,代码行数:35,代码来源:ExportMembers.cs

示例15: LoadDataFromSource

 public List<C5Discount> LoadDataFromSource(System.Web.HttpPostedFileBase file)
 {
     List<C5Discount> c5Discounts = new List<C5Discount>();
     if (file.ContentType.Contains("csv"))
     {
         using (var reader = new StreamReader(file.InputStream))
         {
             using (var csv = new CsvReader(reader, new CsvHelper.Configuration.CsvConfiguration() { Delimiter = ';', Quote = '"', HasHeaderRecord = false, SkipEmptyRecords = false }))
             {
                 c5Discounts = csv.GetRecords<C5Discount>().ToList();
             }
         }
     }
     else
     {
         using (var xlPackage = new ExcelPackage(file.InputStream))
         {
             var worksheet = xlPackage.Workbook.Worksheets.FirstOrDefault();
             if (worksheet == null)
                 throw new NopException("No worksheet found");
             c5Discounts = LoadFromExcelSheet(worksheet);
         }
     }
     return c5Discounts;
 }
开发者ID:Schtolz,项目名称:NopcommerceC5,代码行数:25,代码来源:DiscountImportService.cs


注:本文中的CsvReader.GetRecords方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。