本文整理汇总了C#中CsvReader.GetField方法的典型用法代码示例。如果您正苦于以下问题:C# CsvReader.GetField方法的具体用法?C# CsvReader.GetField怎么用?C# CsvReader.GetField使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类CsvReader
的用法示例。
在下文中一共展示了CsvReader.GetField方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: InsertGopIpIpBlocks
private static void InsertGopIpIpBlocks()
{
Console.WriteLine("inserting ip blocks");
var csv = new CsvReader(new StreamReader("GeoLiteCity-Blocks.csv"));
csv.Read();
var bsonDocuments = new List<BsonDocument>();
while (csv.Read())
{
var document = new BsonDocument();
document.Add(new BsonElement("start_ip_num", long.Parse(csv.GetField(0))));
document.Add(new BsonElement("end_ip_num", long.Parse(csv.GetField(1))));
document.Add(new BsonElement("location_id", int.Parse(csv.GetField(2))));
bsonDocuments.Add(document);
}
var geoIpDataProvider = new GeoIpDataProvider();
geoIpDataProvider.InsertGeoIpBlocks(bsonDocuments);
Console.WriteLine("done");
}
示例2: 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;
}
示例3: Read
public List<Player> Read()
{
string name;
bool won;
try
{
using (FileStream log = new FileStream(fileName, FileMode.OpenOrCreate))
{
using (StreamReader reader = new StreamReader(log))
{
using (var csvReader = new CsvReader(reader))
{
while (csvReader.Read())
{
name = csvReader.GetField<string>(0);
won = csvReader.GetField<bool>(1);
Player player = new Player(name, won);
players.Add(player);
}
}
}
}
return players;
}
catch (Exception)
{
Console.WriteLine("Sorry, no scores have been recorded yet");
return players;
}
}
示例4: GetHistoricalData
public IList<HistoricalData> GetHistoricalData(string underlyingName, DateTime dateTime, int days)
{
DateTime firstDate = dateTime.AddDays(-days);
string startDate = firstDate.ToString("MMM d, yyyy", CultureInfo.InvariantCulture);
string endDate = dateTime.ToString("MMM d, yyyy", CultureInfo.InvariantCulture);
// get the Quote history for the X Months/Years ago (depending of the Maturity)
var result = restTemplate.GetForMessage<string>("/finance/historical?q={code}&startdate={startdate}&enddate={enddate}&output=csv", underlyingName, startDate, endDate);
var csvReader = new CsvReader(new CsvParser(new StringReader(result.Body), new CsvConfiguration { Delimiter = ',', HasHeaderRecord = true }));
var historicalVolatilitySet = new List<HistoricalData>();
HistoricalData previousItem = null;
// read the result, compute the volatility for each days (except the first one)
while (csvReader.Read())
{
var item = new HistoricalData();
item.Date = DateTime.ParseExact(csvReader.GetField("Date"), "d-MMM-yy", CultureInfo.InvariantCulture);
item.Close = double.Parse(csvReader.GetField("Close"), CultureInfo.InvariantCulture);
historicalVolatilitySet.Add(item);
if (previousItem != null)
{
item.Volatility = Math.Log(item.Close / previousItem.Close);
}
previousItem = item;
}
return historicalVolatilitySet;
}
示例5: Main
static void Main(string[] args)
{
foreach (string filepath in System.IO.Directory.EnumerateFiles(@"C:\Users\wildbillcat\Sync\WebSpecs\SKUs", "*.csv"))
{
using (var csv = new CsvReader(System.IO.File.OpenText(filepath)))
{
string[] datePieces = filepath.Split('\\').Last().Split('.')[0].Split('-');
DateTime SalesDate = new DateTime(int.Parse(datePieces[2]), int.Parse(datePieces[0]), int.Parse(datePieces[1]));
SalesDate.AddDays(-1 * (SalesDate.Day - 1));//Ensures Day of the first of the month
int MonthID = (12 * SalesDate.Year) + SalesDate.Month;
while (csv.Read())
{
using(var ctx = new InventoryForcast.Models.ApplicationDbContext())
{
int _sku = csv.GetField<int>(0);
System.Console.WriteLine(string.Concat("SKU: ", _sku, " Date: ", SalesDate));
int _qty_sold = csv.GetField<int>(1);
ctx.MonthlyTotals.Add(new MonthlyTotal()
{
SKU = _sku,
Quantity_Sold = _qty_sold,
Absolute_Quantity_Sold = MonthlyTotal.RemoveSeasonality(_qty_sold, SalesDate.Month),
Date = SalesDate,
Month_Id = MonthID
}
);
ctx.SaveChanges();
}
}
}
}
}
示例6: ImportTranslationsCsv
public static void ImportTranslationsCsv(DataContext db, CsvReader csv, TranslationArea area)
{
while (csv.Read())
{
var code = csv.GetField<string>(0);
var key = csv.GetField<string>(1);
var value = csv.GetField<string>(2);
// ToList is called on purpose for case sensitive search
var translation =
db.Translations.ToList().FirstOrDefault(
t => t.LanguageCode == code && t.Key == key && t.Area == area);
if (translation == null)
{
translation = new Translation
{
LanguageCode = code,
Key = key,
Value = value,
Area = area
};
db.Translations.Add(translation);
}
else
{
translation.Value = value;
}
}
db.SaveChanges();
TranslationHelper.ClearCache();
}
示例7: CreateBet
protected override Bet CreateBet(CsvReader csv)
{
var customerId = csv.GetField<int>("Customer");
var eventId = csv.GetField<int>("Event");
var participantId = csv.GetField<int>("Participant");
var stake = csv.GetField<double>("Stake");
var win = csv.GetField<double>("Win");
var bet = new Bet(customerId, eventId, participantId, stake, win, true);
return bet;
}
示例8: GetFieldByIndexTest
public void GetFieldByIndexTest()
{
var data = new [] { "1", "2" };
var mockFactory = new MockFactory( MockBehavior.Default );
var parserMock = mockFactory.Create<ICsvParser>();
parserMock.Setup( m => m.Read() ).Returns( data );
var reader = new CsvReader( parserMock.Object );
reader.Read();
Assert.AreEqual( 1, reader.GetField<int>( 0 ) );
Assert.AreEqual( 2, reader.GetField<int>( 1 ) );
}
示例9: ValidateFile
public GetProductVariantsFromFileResult ValidateFile(Stream rawFile)
{
var items = new List<BulkStockUpdateDataTransferObject>();
var errors = new List<string>();
if (rawFile != null)
{
using (var file = new CsvReader(new StreamReader(rawFile)))
{
while (file.Read())
{
if (file.FieldHeaders.Length == 4)
{
return GetProductVariantsFromFileResult.Failure(new List<string>
{
"You have attempted to import a file in the warehoused stock format into the simple stock updater."
});
}
string sku = file.GetField<string>(1),
name = file.GetField<string>(0);
string handle = name ?? sku;
var pv = new BulkStockUpdateDataTransferObject
{
Name = name,
SKU = sku
};
if (sku.HasValue())
pv.SKU = sku;
else
errors.Add(string.Format("SKU is required for {0}.", handle));
var stockValue = file.GetField<string>(2);
int stockRemaining;
if (int.TryParse(stockValue, out stockRemaining))
pv.StockRemaining = stockRemaining;
else
errors.Add(string.Format("Stock value for {0} is not a valid number.", handle));
items.Add(pv);
}
}
}
return errors.Any()
? GetProductVariantsFromFileResult.Failure(errors)
: GetProductVariantsFromFileResult.Success(items);
}
示例10: MainWindow_Loaded
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
var reader = File.OpenText("language.csv");
var csv = new CsvReader(reader);
while(csv.Read())
{
var symbol = new LanguageSymbol();
symbol.LanguageName = csv.GetField<string>(0);
symbol.Region = csv.GetField<string>(1);
symbol.Symbol = csv.GetField<string>(2);
LanguageSymbols.Add(symbol);
}
lbLanguageSymbol.ItemsSource = LanguageSymbols;
}
示例11: LoadFromCsv
public void LoadFromCsv(string path)
{
_map.Clear();
using (var tr = File.OpenText(path))
using (var cr = new CsvReader(tr))
{
while (cr.Read())
{
string id = cr.GetField<string>(0);
string value = cr.GetField<string>(1);
_map.Add(id, value);
}
}
}
示例12: SkipEmptyRowTest
public void SkipEmptyRowTest()
{
var rows = new Queue<string[]>();
rows.Enqueue( new[] { "First,Second" } );
rows.Enqueue( new[] { " " } );
rows.Enqueue( new[] { "1", "2" } );
var parser = new ParserMock( rows );
var csv = new CsvReader( parser );
csv.Configuration.ShouldSkipRecord = row => row.All( string.IsNullOrWhiteSpace );
csv.Read();
Assert.AreEqual( "1", csv.GetField( 0 ) );
Assert.AreEqual( "2", csv.GetField( 1 ) );
}
示例13: ParseFileAndGetCsvData
internal static CsvData ParseFileAndGetCsvData(string filePath, UploadConfig config)
{
CsvConfiguration configuration = new CsvConfiguration();
configuration.HasHeaderRecord = true;
CsvReader csvReader = new CsvReader(new StreamReader(filePath), configuration);
string[] header = default(string[]);
List<string[]> rows = new List<string[]>();
string[] row;
while (csvReader.Read())
{
header = csvReader.FieldHeaders;
row = new string[header.Length];
for (int j = 0; j < header.Length; j++)
{
row[j] = csvReader.GetField(j);
}
rows.Add(row);
}
return new CsvData { Header = header, Rows = rows };
}
示例14: ParseFileData
public static CurrenciesFactorsPer1UnitInUsd ParseFileData(TextReader fileReader)
{
var factors = new CurrenciesFactorsPer1UnitInUsd();
var reader = new CsvReader(fileReader, CreateCsvReaderConfiguration());
while (reader.Read())
{
var symbol = reader.GetField(0);
Currency currency;
try { currency = (Currency) Enum.Parse(typeof (Currency), symbol.ToUpper()); }
catch { continue; }
if (currency == Currency.UNKNOWN || currency == Currency.USD)
continue;
decimal factor;
if (!Decimal.TryParse(reader.GetField(1), NumberStyles.Number, CultureInfo.InvariantCulture, out factor)
|| factor <= 0m)
continue;
factors[currency] = factor;
}
return factors;
}
示例15: do_it
public void do_it()
{
string path = @"c:\work\id-list.csv";
using (var reader = new StreamReader(path))
{
var csv = new CsvReader(reader);
csv.Configuration.HasHeaderRecord = false;
var list = new List<Tuple<string, List<string>>>();
while (csv.Read())
{
var id = csv.GetField<string>(0);
var resourcePaths = csv.CurrentRecord.Skip(1)
.Where(value => value.IsNotBlank())
.ToList();
list.Add(new Tuple<string, List<string>>(id, resourcePaths));
}
list.Count.Should().Be(2);
list[0].Item1.Should().Be("id1");
list[0].Item2.Should().Contain(@"x:\some\path\2");
}
}