本文整理汇总了C#中CsvReader类的典型用法代码示例。如果您正苦于以下问题:C# CsvReader类的具体用法?C# CsvReader怎么用?C# CsvReader使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
CsvReader类属于命名空间,在下文中一共展示了CsvReader类的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();
}
}
}
示例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();
}
}
示例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();
}
示例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;
}
示例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;
}
示例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 );
}
示例7: ArgumentTestCopyCurrentRecordTo3
public void ArgumentTestCopyCurrentRecordTo3()
{
using (CsvReader csv = new CsvReader(new StringReader(CsvReaderSampleData.SampleData1), false))
{
csv.CopyCurrentRecordTo(new string[1], 1);
}
}
示例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();
}
示例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;
}
示例10: ArgumentTestCtor4
public void ArgumentTestCtor4()
{
using (CsvReader csv = new CsvReader(new StringReader(""), false, 123))
{
Assert.AreEqual(123, csv.BufferSize);
}
}
示例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);
}
示例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;
}
示例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;
}
示例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;
}
}
示例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();
}
}