• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# CsvReader类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中CsvReader的典型用法代码示例。如果您正苦于以下问题:C# CsvReader类的具体用法?C# CsvReader怎么用?C# CsvReader使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



CsvReader类属于命名空间,在下文中一共展示了CsvReader类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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: 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


示例3: 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


示例4: BatchProcessFbcFayetteville

        private static int? BatchProcessFbcFayetteville(CsvReader csv, DateTime date, int? fundid)
        {
            var cols = csv.GetFieldHeaders();
            BundleHeader bh = null;
            var firstfund = FirstFundId();
            var fund = fundid ?? firstfund;

            while (csv.ReadNextRecord())
            {
                if (csv[6].StartsWith("Total Checks"))
                    continue;
                var routing = csv[4];
                var account = csv[5];
                var checkno = csv[6];
                var amount = csv[7];

                if (bh == null)
                    bh = GetBundleHeader(date, DateTime.Now);

                var bd = AddContributionDetail(date, fund, amount, checkno, routing, account);
                bh.BundleDetails.Add(bd);
            }
            if (bh == null)
                return null;
            FinishBundle(bh);
            return bh.BundleHeaderId;
        }
开发者ID:hkouns,项目名称:bvcms,代码行数:27,代码来源:FbcFayetteville.cs


示例5: ParseData

        public bool ParseData(string filename)
        {
            using (CsvReader csv = new CsvReader(new StreamReader(filename), true))
            {
                int fieldCount = csv.FieldCount;

                int rollFieldIndex = csv.GetFieldIndex("Roll Input (ratio)");
                int pitchFieldIndex = csv.GetFieldIndex("Pitch Input (ratio)");
                int yawFieldIndex = csv.GetFieldIndex("Yaw Input (ratio)");

                if (rollFieldIndex == -1 || pitchFieldIndex == -1 || yawFieldIndex == -1)
                {
                    return false;
                }

                int currentIndex = 0;

                while (csv.ReadNextRecord() && currentIndex < n_fileRowCount)
                {
                    f_timeInputArray[currentIndex] = float.Parse(csv[0]);
                    f_rollInputArray[currentIndex] = float.Parse(csv[rollFieldIndex]);
                    f_pitchInputArray[currentIndex] = float.Parse(csv[pitchFieldIndex]);
                    f_yawInputArray[currentIndex] = float.Parse(csv[yawFieldIndex]);
                    f_maxTime = f_timeInputArray[currentIndex];
                    currentIndex++;
                }
                f_startTime = f_timeInputArray[0];
                n_dataPoints = currentIndex;
            }

            return true;
        }
开发者ID:jplumpto,项目名称:KatanaSimTools-V2012,代码行数:32,代码来源:FlightTestData.cs


示例6: BooleanTypeConverterTest

        public void BooleanTypeConverterTest()
        {
            var stream = new MemoryStream();
            var writer = new StreamWriter( stream );

            writer.WriteLine( "BoolColumn,BoolNullableColumn,StringColumn" );
            writer.WriteLine( "true,true,1" );
            writer.WriteLine( "True,True,2" );
            writer.WriteLine( "1,1,3" );
            writer.WriteLine( "false,false,4" );
            writer.WriteLine( "False,False,5" );
            writer.WriteLine( "0,0,6" );

            writer.Flush();
            stream.Position = 0;

            var reader = new StreamReader( stream );
            var csvReader = new CsvReader( reader );

            var records = csvReader.GetRecords<TestBoolean>().ToList();

            Assert.IsTrue( records[0].BoolColumn );
            Assert.IsTrue( records[0].BoolNullableColumn);
            Assert.IsTrue( records[1].BoolColumn);
            Assert.IsTrue( records[1].BoolNullableColumn );
            Assert.IsTrue( records[2].BoolColumn );
            Assert.IsTrue( records[2].BoolNullableColumn );
            Assert.IsFalse( records[3].BoolColumn );
            Assert.IsFalse( records[3].BoolNullableColumn);
            Assert.IsFalse( records[4].BoolColumn );
            Assert.IsFalse( records[4].BoolNullableColumn );
            Assert.IsFalse( records[5].BoolColumn );
            Assert.IsFalse( records[5].BoolNullableColumn );
        }
开发者ID:Orcomp,项目名称:CsvHelper,代码行数:34,代码来源:CsvReaderTests.cs


示例7: ArgumentTestCopyCurrentRecordTo3

 public void ArgumentTestCopyCurrentRecordTo3()
 {
     using (CsvReader csv = new CsvReader(new StringReader(CsvReaderSampleData.SampleData1), false))
     {
         csv.CopyCurrentRecordTo(new string[1], 1);
     }
 }
开发者ID:jboolean,项目名称:RIT-Bus,代码行数:7,代码来源:CsvReaderTest.cs


示例8: 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


示例9: BatchProcessAbundantLife

        private static int? BatchProcessAbundantLife(CsvReader csv, DateTime date, int? fundid)
        {
            BundleHeader bh = null;
            var fid = fundid ?? BatchImportContributions.FirstFundId();

            var prevbatch = "";
            while (csv.ReadNextRecord())
            {
                var batch = csv[5];
                if (bh == null || batch != prevbatch)
                {
                    if (bh != null)
                        BatchImportContributions.FinishBundle(bh);
                    bh = BatchImportContributions.GetBundleHeader(date, DateTime.Now);
                    prevbatch = batch;
                    continue; // the first row of a batch is a total row
                }
                var amount = csv[3];
                var routing = csv[8];
                var account = csv[9];
                var checkno = csv[10];
                var bd = BatchImportContributions.AddContributionDetail(date, fid, amount, checkno, routing, account);
                bh.BundleDetails.Add(bd);
            }

            BatchImportContributions.FinishBundle(bh);

            return bh?.BundleHeaderId;
        }
开发者ID:stevesloka,项目名称:bvcms,代码行数:29,代码来源:AbundantLifeImporter.cs


示例10: ArgumentTestCtor4

		public void ArgumentTestCtor4()
		{
			using (CsvReader csv = new CsvReader(new StringReader(""), false, 123))
			{
				Assert.AreEqual(123, csv.BufferSize);
			}
		}
开发者ID:lanterna72,项目名称:CsvReader,代码行数:7,代码来源:CsvReaderTest.cs


示例11: CheckSampleData1

		public static void CheckSampleData1(CsvReader csv, bool readToEnd)
		{
			if (readToEnd)
			{
				Assert.AreEqual(CsvReaderSampleData.SampleData1FieldCount, csv.FieldCount);

				if (csv.HasHeaders)
				{
					Assert.AreEqual(0, csv.GetFieldIndex(SampleData1Header0));
					Assert.AreEqual(1, csv.GetFieldIndex(SampleData1Header1));
					Assert.AreEqual(2, csv.GetFieldIndex(SampleData1Header2));
					Assert.AreEqual(3, csv.GetFieldIndex(SampleData1Header3));
					Assert.AreEqual(4, csv.GetFieldIndex(SampleData1Header4));
					Assert.AreEqual(5, csv.GetFieldIndex(SampleData1Header5));
				}
				
				Assert.AreEqual(-1, csv.CurrentRecordIndex);

				int recordCount = 0;

				while (csv.ReadNextRecord())
				{
					CheckSampleData1(csv.CurrentRecordIndex, csv);
					recordCount++;
				}

				if (csv.HasHeaders)
					Assert.AreEqual(CsvReaderSampleData.SampleData1RecordCount, recordCount);
				else
					Assert.AreEqual(CsvReaderSampleData.SampleData1RecordCount + 1, recordCount);
			}
			else
				CheckSampleData1(csv.CurrentRecordIndex, csv);
		}
开发者ID:jhgbrt,项目名称:netcsv,代码行数:34,代码来源:CsvReaderSampleData.cs


示例12: ReadTestInput

        private List<BondCalculatorModel> ReadTestInput(string testfile,bool expectYield)
        {
            List<BondCalculatorModel> inputs = new List<BondCalculatorModel>();

            using (StreamReader reader = File.OpenText(testfile))
            {
                CsvReader csv = new CsvReader(reader);
                while (csv.Read())
                {
                    BondCalculatorModel model = new BondCalculatorModel();

                    model.CouponRate = csv.GetField<decimal>(0);
                    model.YearsToMaturity = csv.GetField<int>(1);
                    model.Frequency = csv.GetField<int>(2);
                    model.FaceValue = csv.GetField<decimal>(3);
                    if (expectYield)
                    {
                        model.PresentValue = csv.GetField<decimal>(4);
                        model.Yield = csv.GetField<decimal>(5);
                    }
                    else
                    {
                        model.Yield = csv.GetField<decimal>(4);
                        model.PresentValue = csv.GetField<decimal>(5);
                    }

                    inputs.Add(model);
                }

            }
            return inputs;
        }
开发者ID:desai123in,项目名称:BondCalculator,代码行数:32,代码来源:RegressionTest.cs


示例13: loadTrivia

        bool loadTrivia()
        {
            var config   = app.Settings.Configs[configTrivia];
            var fileName = config.Get(keyDatabase, fileDatabase);

            if ( !File.Exists(fileName) )
            {
                Log.Warn(tag, "Could not load database; '{0}' is missing", fileName);
                return false;
            }

            var file        = new StreamReader(fileName);
            var reader      = new CsvReader(file);
            var fileEntries = reader.GetRecords<TriviaEntry>();
            var list        = new List<TriviaEntry>();

            foreach ( var entry in fileEntries )
            {
                if ( entry.Question.Trim() == "" || entry.Answer.Trim() == "" )
                    continue;

                if ( entry.Wrong.Trim() == "" )
                    entry.Wrong = null;

                list.Add(entry);
            }

            entries = shuffleEntries(list);
            reader.Dispose();
            file  .Dispose();
            Log.Debug(tag, "Loaded trivia database '{0}', {1} entries", fileName, entries.Length);
            return true;
        }
开发者ID:VirtualParadise,项目名称:VPServices,代码行数:33,代码来源:Trivia.Entries.cs


示例14: GetStudentData

        public static List<Tuple<int, string, int, string>> GetStudentData()
        {

            //C:\Users\Heather\Documents\Students.csv
            using (var sr = new StreamReader("Students.csv"))
            {
                var reader = new CsvReader(sr);
                //return reader.GetRecords<StudentDataReader>();
                IEnumerable<StudentDataReader> students = reader.GetRecords<StudentDataReader>();
                List<Tuple<int, string, int, string>> allStudents = new List<Tuple<int, string, int, string>>();
                //Dictionary<int, Tuple<int, string, string>> allStudents = new Dictionary<int, Tuple<int, string, string>>();
                //return students;
                foreach (var student in students)
                {
                    allStudents.Add(new Tuple<int, string, int, string>(
                        student.user_id,
                        student.user_name,
                        student.course_id,
                        student.state
                        ));
                }

                return allStudents;
            }

        }
开发者ID:mlegendre,项目名称:instructuretest,代码行数:26,代码来源:Program.cs


示例15: FetchShowNamesFromEpGuides

 public ShowInfoCache[] FetchShowNamesFromEpGuides()
 {
     var request = WebRequest.Create("http://epguides.com/common/allshows.txt");
     var response = request.GetResponse();
     using (var r = new StreamReader(response.GetResponseStream()))
     {
         //title,directory,tvrage,start date,end date,number of episodes,run time,network,country
         var parser = new CsvReader(r);
         var ids = new HashSet<string>(); //The datasource is a bit crap so we need to remove their dupes
         var result = new List<ShowInfoCache>();
         while (parser.Read())
         {
             DateTimeOffset d;
             var hasEnded = false;
             if(DateTimeOffset.TryParseExact(
                 parser.GetField("end date"),
                 "MMM yyyy", CultureInfo.GetCultureInfo("en-US"), DateTimeStyles.None, out d))
             {
                 hasEnded = true;
             }
             var id = ShowInfoCache.IdFromSourceId(parser.GetField("tvrage"));
             if (!ids.Contains(id))
                 result.Add(new ShowInfoCache
                                {
                                    Id = id,
                                    Name = parser.GetField("title"),
                                    HasEnded = hasEnded
                                });
             ids.Add(id);
         }
         return result.ToArray();
     }
 }
开发者ID:alundgren,项目名称:alun-tv,代码行数:33,代码来源:EpGuideShowSource.cs


示例16: GetRecordGenericTest

		public void GetRecordGenericTest()
		{
			var parser = new ParserMock
			{
				{ "Id", "Name" },
				{ "a", "b" },
				null
			};

			var reader = new CsvReader( parser );
			reader.Read();
			try
			{
				reader.GetRecord<Simple>();
				Assert.Fail();
			}
			catch( CsvTypeConverterException ex )
			{
				var expected = "Row: '2' (1 based)\r\n" +
				        "Type: 'CsvHelper.Tests.Exceptions.ExceptionMessageTests+Simple'\r\n" +
				        "Field Index: '0' (0 based)\r\n" +
				        "Field Name: 'Id'\r\n" +
				        "Field Value: 'a'\r\n";
				Assert.AreEqual( expected, ex.Data["CsvHelper"] );

			}
		}
开发者ID:Core2D,项目名称:CsvHelper,代码行数:27,代码来源:ExceptionMessageTests.cs


示例17: btnUpload_Click

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        try
        {
            using (CsvReader csv = new CsvReader(new StreamReader(fileUpload.FileContent), true))
            {
                int count = 0;
                DepartmentOrderTableAdapters.DepartmentOrderRowTableAdapter orderTA = new DepartmentOrderTableAdapters.DepartmentOrderRowTableAdapter();

                while (csv.ReadNextRecord())
                {
                    string fullAddress = csv[0] + csv[1] + csv[2] + csv[3] + csv[4] + csv[5];
                    IEnumerator iEnumerator = orderTA.InsertAndReturn(false, (int)Session[WebConstants.Session.REG_DEPT_ID], (int)Session[WebConstants.Session.REG_CO_ID], WebConstants.Default.NOT_SET, WebConstants.Default.NOT_SET,
                        WebConstants.Default.NOT_SET, DateTime.Now, 0, DateTime.Now.AddYears(1), false, "", csv[0], csv[1], csv[2],
                        csv[3], csv[4], csv[5], fullAddress, "", false, false, false, null, null, null, null, (int)Session[WebConstants.Session.REG_USER_ID], DateTime.Now, (int)Session[WebConstants.Session.REG_USER_ID], DateTime.Now).GetEnumerator();
                    if (iEnumerator.MoveNext())
                    {
                        count++;
                    }
                }

                SetInfoMessage(count + " folders added to the system.");
            }
        }
        catch
        {
            SetErrorMessage("Error processing the file. Please check its contents. File should be CSV and in the format shown below");
        }
    }
开发者ID:ali-codehoppers,项目名称:unchsunchs,代码行数:29,代码来源:UploadOrders.aspx.cs


示例18: Index

        public ActionResult Index(HttpPostedFileBase file)
        {
            List<Register> register = new List<Register>();

            //get data from csv
            try {
                if (file.ContentLength > 0)
                {
                    IEnumerable<Register> records;
                    using (var reader = new CsvReader(new StreamReader(file.FileName)))
                    { 
                        //no header record.  This property is trure by default.
                        reader.Configuration.HasHeaderRecord = false;

                        //use a mapping file to pull the data into the class correctly by index
                        reader.Configuration.RegisterClassMap<RegisterClassMapping>();

                        //Fill Class from comma delimited file
                        records = reader.GetRecords<Register>();

                        //need to have the records in a list so converting from the ienumberable csvhelper needed
                        register = records.ToList();
                    }                    
                }
            }
            catch (Exception ex) {
                ViewBag.Error = "Upload Failed: " + ex.Message;
            }
            
            return View(register);
        }
开发者ID:jchadman,项目名称:CashRegister-1,代码行数:31,代码来源:HomeController.cs


示例19: 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


示例20: CsvImporter

 public CsvImporter(string csvFilePath, string schemaFilePath, IUserRepository repository)
 {
     _csvFilePath = csvFilePath;
     _repository = repository;
     _reader = new CsvReader(File.OpenText(csvFilePath), true);
     ValidateAgainstSchema(_reader, schemaFilePath);
 }
开发者ID:mmann2943,项目名称:berry-patch,代码行数:7,代码来源:CsvImporter.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# CsvRecordReader类代码示例发布时间:2022-05-24
下一篇:
C# CsvParser类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap