本文整理汇总了C#中Microsoft.VisualBasic.FileIO.TextFieldParser类的典型用法代码示例。如果您正苦于以下问题:C# TextFieldParser类的具体用法?C# TextFieldParser怎么用?C# TextFieldParser使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
TextFieldParser类属于Microsoft.VisualBasic.FileIO命名空间,在下文中一共展示了TextFieldParser类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetDataTableColumns
public DataTable GetDataTableColumns(string csv_file_path)
{
DataTable csvData = new DataTable();
try
{
using (TextFieldParser csvReader = new TextFieldParser(csv_file_path))
{
csvReader.SetDelimiters(new string[] { "," });
csvReader.HasFieldsEnclosedInQuotes = true;
string[] colFields = csvReader.ReadFields();
for (int i = 0; i < colFields.Length; i++)
{
colFields[i] = this.RemoveSpecialCharacters(colFields[i]);
}
foreach (string column in colFields)
{
DataColumn datecolumn = new DataColumn(column);
datecolumn.AllowDBNull = true;
csvData.Columns.Add(datecolumn);
}
}
}
catch (Exception ex)
{
//TO DO
}
return csvData;
}
示例2: Main
static void Main(string[] args)
{
PrintHeading();
if (!File.Exists(Settings.Default.ImportFile))
{
Console.WriteLine("Could not find data file at '" + Settings.Default.ImportFile);
return;
}
if (File.Exists(Settings.Default.OutputFile))
File.Delete(Settings.Default.OutputFile);
var parser = new TextFieldParser(Settings.Default.ImportFile);
using (var sw = new StreamWriter(Settings.Default.OutputFile))
{
parser.SetDelimiters(new[] {"\t"});
// Consume first row.
if (!parser.EndOfData) parser.ReadFields();
while (!parser.EndOfData)
{
var fields = parser.ReadFields();
var call = new SatComCallIndentifier(fields);
Console.WriteLine(call.GetSqlInsert());
sw.WriteLine(call.GetSqlInsert());
}
}
Console.WriteLine();
Console.WriteLine("Outputted sql to: " + Settings.Default.OutputFile);
Console.ReadLine();
}
示例3: CsvReader
public CsvReader( string path, Encoding encoding )
{
Info = new FileInfo( path );
file = new TextFieldParser( path, encoding );
file.TextFieldType = FieldType.Delimited;
file.Delimiters = new string[] { "," };
}
示例4: DataTableFromCSV
private DataTable DataTableFromCSV(string path)
{
var data = new DataTable();
using (var parser = new TextFieldParser(path))
{
parser.SetDelimiters(new[] { "," });
parser.HasFieldsEnclosedInQuotes = true;
try
{
var columns = parser.ReadFields();
foreach (string column in columns)
{
var dataColumn = new DataColumn(column);
dataColumn.AllowDBNull = true;
data.Columns.Add(dataColumn);
}
while (!parser.EndOfData)
{
var row = parser.ReadFields();
data.Rows.Add(row);
}
}
catch (MalformedLineException)
{
throw;
}
}
return data;
}
示例5: LeMondGForceSTNCsvDataProvider
public LeMondGForceSTNCsvDataProvider(string sourceName, TextFieldParser parser, string[] firstRow)
: base(parser)
{
if (firstRow.Length < 6)
{
throw new Exception(string.Format("Invalid gforce STN header. Header = '{0}'", string.Join(",", firstRow)));
}
firmwareVersion = LeMondGForceSTNCsvDataProvider.ParseFirmwareVersion(firstRow[1]);
int year, month, day;
LeMondGForceCsvDataProvider.ParseDate(firstRow[4], out year, out month, out day);
int hour, minute;
LeMondGForceCsvDataProvider.ParseTime(firstRow[5], out hour, out minute);
StartTime = new DateTime(year, month, day, hour, minute, 0, DateTimeKind.Local);
if (Parser.EndOfData)
{
throw new Exception(string.Format("The file {0} does not seem to be a valid LeMond .csv file because it is missing the data field headers.", sourceName));
}
firstRow = Parser.ReadFields();
if (!(firstRow.Length >= 7 &&
firstRow[0] == "TIME" &&
firstRow[1] == "SPEED" &&
firstRow[2] == "DIST" &&
firstRow[3] == "POWER" &&
firstRow[4] == "HEART RATE" &&
firstRow[5] == "RPM" &&
firstRow[6] == "CALORIES"))
{
throw new Exception(string.Format("The file {0} does not seem to be a valid LeMond .csv file because it does not contain the correct data fields.", sourceName));
}
}
示例6: ReadCsv
public static IEnumerable<object> ReadCsv(Stream stream)
{
var parser = new TextFieldParser(stream)
{
TextFieldType = FieldType.Delimited,
Delimiters = new[] { "," },
HasFieldsEnclosedInQuotes = true,
TrimWhiteSpace = true
};
string[] fields = parser.ReadFields();
while (!parser.EndOfData)
{
string[] row = parser.ReadFields();
var data = (IDictionary<string, object>)new ExpandoObject();
for (int i = 0; i < fields.Length; i++)
{
data[fields[i]] = row[i];
}
yield return data;
}
}
示例7: Main
static void Main()
{
List<MoonPhase> moonPhases = new List<MoonPhase>();
using (TextFieldParser parser = new TextFieldParser(@"SQMData.csv"))
{
parser.TextFieldType = FieldType.Delimited;
// Значения во входном файле разделены запятыми
parser.SetDelimiters(",");
// Указываем что следует игнорировать строки начинающиеся с #
parser.CommentTokens = new string[] {"#"};
DateTime prevSkyclock = DateTime.MinValue;
while (!parser.EndOfData)
{
string[] fields = null;
try
{
fields = parser.ReadFields();
}
catch (MalformedLineException)
{
// Игнорируем "плохие" строки
continue;
}
// Поля в файле
// 0 - Year
// 1 - Month
// 2 - Day
// 3 - Local_time
// 4 - day_of_year
// 5 - hour_of_day
// 6 - Sky_Quality_(mag/arc_sec_**2)
// 7 - SQM_temperature_(Celsius)
// 8 - cloud_cover_(%)
// 9 - seeing_(1-5)
// 10 - transparency_(1-5)
// 11 - skyclock_time/date_used
// 12 - sunrise
// 13 - sunset
// 14 - moonrise
// 15 - moonset
// 16 - moonphase
DateTime skyclock = DateTime.ParseExact(fields[11], "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
int moonPhase = int.Parse(fields[16]);
if (prevSkyclock != skyclock.Date)
{
moonPhases.Add(new MoonPhase { Date = skyclock.Date, Phase = moonPhase });
prevSkyclock = skyclock.Date;
}
}
}
foreach (MoonPhase phase in moonPhases)
{
Console.WriteLine("{0:d} - {1}", phase.Date, phase.Phase);
}
}
示例8: Load
/// <summary>
/// inladen van het CSV bestand met verschillende diersoorten
/// </summary>
/// <returns>lijst van ingeladen dieren</returns>
public List<Diersoort> Load()
{
List<Diersoort> loadedAnimals = new List<Diersoort>();
//Get all the animal names from the local storage
using (TextFieldParser parser = new TextFieldParser(FilePath + "broedvogels.csv"))
{
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
while (!parser.EndOfData)
{
//Processing row
string[] fields = parser.ReadFields();
foreach (string field in fields)
{
string[] columns = field.Split(';');
string[] startDatetime = columns[2].Split('-');
string[] endDatetime = columns[3].Split('-');
DateTime sdt = new DateTime(2000, Convert.ToInt32(startDatetime[1]), Convert.ToInt32(startDatetime[0]));
DateTime edt = new DateTime(2000, Convert.ToInt32(endDatetime[1]), Convert.ToInt32(endDatetime[0]));
Diersoort toAdd = new Vogel(
columns[0],
columns[1],
sdt,
edt,
Convert.ToInt32(columns[4]));
loadedAnimals.Add(toAdd);
}
}
}
return loadedAnimals;
}
示例9: Create
public static ILeMondDataProvider Create(SourcedStream sourcedStream)
{
var parser = new TextFieldParser(sourcedStream.Stream);
parser.TextFieldType = FieldType.Delimited;
parser.Delimiters = new[] { "," };
if (parser.EndOfData)
{
throw new Exception(string.Format("The file {0} does not seem to be a valid LeMond .csv file because it is empty.", sourcedStream.Source));
}
var row = parser.ReadFields();
if (!(row.Length >= 1 && row[0] == "LeMond"))
{
throw new Exception(string.Format("The file {0} does not seem to be a valid LeMond .csv file because it doesn't say 'LeMond' in the first field.", sourcedStream.Source));
}
if (row.Length >= 4 && row[3] == "gforce")
{
return new LeMondGForceCsvDataProvider(sourcedStream.Source, parser, row);
}
if (row.Length >= 4 && row[3] == "STN")
{
return new LeMondGForceSTNCsvDataProvider(sourcedStream.Source, parser, row);
}
else if (row.Length >= 2 && row[1] == "Revolution")
{
return new LeMondRevolutionCsvDataProvider(sourcedStream.Source, parser, row);
}
throw new Exception(string.Format("Not a recognized LeMond device. Header = '{0}'", string.Join(",", row)));
}
示例10: ProviderMgr
public ProviderMgr()
{
TextFieldParser parser = new TextFieldParser(@"" + Directory.GetCurrentDirectory() + "\\dnscrypt-resolvers.csv");
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
while (!parser.EndOfData)
{
ProviderItem providerItem = new ProviderItem();
string[] fields = parser.ReadFields();
providerItem.setName(fields[0]);
providerItem.setFullName(fields[1]);
providerItem.setDescription(fields[2]);
providerItem.setLocation(fields[3]);
providerItem.setCoordinates(fields[4]);
providerItem.setURL(fields[5]);
providerItem.setVersion(fields[6]);
providerItem.setDNSSEC(fields[7]);
providerItem.setNoLogs(fields[8]);
providerItem.setNamecoin(fields[9]);
providerItem.setAddress(fields[10]);
providerItem.setProviderName(fields[11]);
providerItem.setPublicKey(fields[12]);
providerItem.setPublicKeyTXT(fields[13]);
providerList.Add(providerItem);
}
parser.Close();
// Remove first line from CVS (Name, etc, etc)
providerList.RemoveAt(0);
}
示例11: Read
public IEnumerable<Brand> Read()
{
using (TextFieldParser parser = new TextFieldParser(path))
{
parser.CommentTokens = new string[] { "#" };
parser.SetDelimiters(new string[] { ";" });
parser.HasFieldsEnclosedInQuotes = true;
// Skip over header line.
parser.ReadLine();
while (!parser.EndOfData)
{
string[] fields = parser.ReadFields();
yield return new Brand()
{
Name = fields[0],
FactoryLocation = fields[1],
EstablishedYear = int.Parse(fields[2]),
Profit = double.Parse(fields[3], swedishCulture)
};
}
}
}
示例12: StartTransactionImport
/// <summary>
/// Imports the given csv file
/// </summary>
public void StartTransactionImport(string csvfile)
{
api = new SimpleRestApi(ConfigurationManager.AppSettings["ovservice"]);
log4net.Config.XmlConfigurator.Configure();
parser = new TextFieldParser(csvfile) {Delimiters = new[] {","}};
parser.ReadFields();
while (!parser.EndOfData)
{
IList<string> csvFields = parser.ReadFields();
if (HasValidNumberOfFields(csvFields))
{
Line CSVLine = new Line(csvFields);
try
{
Retry.Repeat(3)
.WithPolling(TimeSpan.FromSeconds(1))
.WithTimeout(TimeSpan.FromSeconds(10))
.Until(() => PostCSVLine(CSVLine));
}
catch (Exception)
{
log.DebugFormat("Max retries reached, skipping line: {0}", CSVLine);
}
} else
{
log.ErrorFormat("Invalid line is skipped! (Incorrect number of fields) {0}", string.Join(",", csvFields));
}
}
}
示例13: ReportFile
public ReportFile(string path)
{
fileInfo = new FileInfo(path);
if (!fileInfo.Exists)
{
CreateReportFile(fileInfo);
}
var parser = new TextFieldParser(path) { Delimiters = new[] { "," } };
if (!parser.EndOfData)
{
var headerFields = parser.ReadFields();
var langList = new List<string>();
// skip Date/Time and Word Count column headers
for (var i = 2; i < headerFields.Length; ++i)
{
var lang = headerFields[i];
langList.Add(lang);
langs.Add(lang);
}
while (!parser.EndOfData)
{
rows.Add(new ReportRow(langList.ToArray(), parser.ReadFields()));
}
}
parser.Close();
}
示例14: Read
public TradeDataEntry[] Read(string filePath)
{
using (var parser = new TextFieldParser(filePath))
{
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
var tradeDataEntries = new List<TradeDataEntry>();
while (!parser.EndOfData)
{
var fields = parser.ReadFields();
if (fields != null)
{
if (fields.Length != 6)
{
return new TradeDataEntry[] { };
}
var date = DateTime.ParseExact(fields[0], "yyyy-M-d", null);
var open = double.Parse(fields[1], CultureInfo.InvariantCulture);
var high = double.Parse(fields[2], CultureInfo.InvariantCulture);
var low = double.Parse(fields[3], CultureInfo.InvariantCulture);
var close = double.Parse(fields[4], CultureInfo.InvariantCulture);
var volume = int.Parse(fields[5]);
tradeDataEntries.Add(new TradeDataEntry(date, open, high, low, close, volume));
}
}
return tradeDataEntries.ToArray();
}
}
示例15: ReadFile
public void ReadFile()
{
if (FilePath == null) return;
var parser = new TextFieldParser(FilePath)
{
TextFieldType = FieldType.Delimited,
CommentTokens = new[] {"#"}
};
parser.SetDelimiters(",");
parser.HasFieldsEnclosedInQuotes = false;
parser.ReadLine();
while (!parser.EndOfData)
{
var row = parser.ReadFields();
if (row == null) continue;
var newLine = new List<string>(row.Length);
newLine.AddRange(row);
_data.Add(newLine);
}
}