本文整理汇总了C#中Microsoft.VisualBasic.FileIO.TextFieldParser.ReadFields方法的典型用法代码示例。如果您正苦于以下问题:C# TextFieldParser.ReadFields方法的具体用法?C# TextFieldParser.ReadFields怎么用?C# TextFieldParser.ReadFields使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.VisualBasic.FileIO.TextFieldParser
的用法示例。
在下文中一共展示了TextFieldParser.ReadFields方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Import
public void Import(string translationCSVPath)
{
patchDict = new Dictionary<int, string>();
using (TextFieldParser parser = new TextFieldParser(translationCSVPath))
{
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
parser.ReadFields(); // Skip header
int i = 0;
while (!parser.EndOfData)
{
string[] fields = parser.ReadFields();
string translatedString = fields[1];
if (!string.IsNullOrEmpty(translatedString))
{
patchDict.Add(i, fields[1]);
}
i++;
}
}
}
示例2: Create
public static XtrainerDataProvider Create(SourcedStream sourcedStream)
{
var parser = new TextFieldParser(sourcedStream.Stream)
{
TextFieldType = FieldType.Delimited,
Delimiters = new[] {","}
};
if (parser.EndOfData)
{
throw new Exception(string.Format("The file {0} does not seem to be a valid xtrainer .csvx file because it is empty.", sourcedStream.Source));
}
var rows = parser.ReadFields();
if (!(rows.Length >= 1 && rows[0] == "ver"))
{
throw new Exception(string.Format("The file {0} does not seem to be a valid xtrainer .csvx file because it doesn't say 'ver' in the first field.", sourcedStream.Source));
}
rows = parser.ReadFields();
int dummy;
if (rows.Length == 5 && int.TryParse(rows[0], out dummy))
{
var startDateTime = new DateTime(int.Parse(rows[0]), int.Parse(rows[1]), int.Parse(rows[2]),
int.Parse(rows[3]), int.Parse(rows[4]), 0);
parser.ReadFields();
return new XtrainerDataProvider(parser,startDateTime);
}
return new XtrainerDataProvider(parser);
}
示例3: 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();
}
示例4: Parse
/// <summary>
/// Parses CSV file.
/// </summary>
/// <param name="file">File to parse.</param>
/// <param name="entityNameField">Name of a field containing entity names.</param>
/// <returns>Parsed entities</returns>
public IEnumerable<object> Parse(string file, string entityNameField)
{
using (var parser = new TextFieldParser(file))
{
parser.SetDelimiters(new[] { "," });
parser.HasFieldsEnclosedInQuotes = true;
parser.TrimWhiteSpace = true;
// Read header.
var columns = parser.ReadFields().Select(col => col.ToLowerInvariant()).ToArray();
entityNameField = entityNameField.ToLowerInvariant();
if (columns.FirstOrDefault(col => col == entityNameField) == null)
{
throw new Exception("File '" + file + "' does not contain required field '" + entityNameField + "'");
}
// Key is field name, value is field value.
var row = new Dictionary<string, string>();
// Parse rows.
while (!parser.EndOfData)
{
var values = parser.ReadFields();
for (int i = 0; i < columns.Length; i++)
{
row[columns[i]] = values[i];
}
yield return CreateEntity(row, entityNameField);
}
}
}
示例5: 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));
}
}
}
示例6: 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();
}
示例7: TextFieldParserMethod
// TextFieldParser Method
private static List<string> TextFieldParserMethod(string SourceFilePath)
{
List<string> ResultList = new List<string>();
// Parser
using (TextFieldParser parser = new TextFieldParser(SourceFilePath))
{
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
// Find Index
string[] header = parser.ReadFields();
int physicalDeliveryOfficeNameIndex = Array.IndexOf(header, "physicalDeliveryOfficeName");
int nameIndex = Array.IndexOf(header, "name");
int titleIndex = Array.IndexOf(header, "title");
string[] CurrentRow;
while (!parser.EndOfData)
{
//Processing row
string[] fields = parser.ReadFields();
CurrentRow = new string[3] { fields[physicalDeliveryOfficeNameIndex], fields[nameIndex], fields[titleIndex] };
if (!string.IsNullOrEmpty(CurrentRow[0]))
ResultList.Add(string.Join(",", CurrentRow));
}
}
return ResultList;
}
示例8: GetDataTabletFromCSVFile
/// <summary>
/// http://stackoverflow.com/questions/16606753/populating-a-dataset-from-a-csv-file
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static DataTable GetDataTabletFromCSVFile(string filePath)
{
DataTable csvData = new DataTable();
try {
using (TextFieldParser csvReader = new TextFieldParser(filePath))
{
csvReader.SetDelimiters(new string[] { "," });
csvReader.HasFieldsEnclosedInQuotes = true;
string[] colFields = csvReader.ReadFields();
foreach (string column in colFields)
{
DataColumn datecolumn = new DataColumn(column);
datecolumn.AllowDBNull = true;
csvData.Columns.Add(datecolumn);
}
while (!csvReader.EndOfData)
{
string[] fieldData = csvReader.ReadFields();
//Making empty value as null
for (int i = 0; i < fieldData.Length; i++)
{
if (fieldData[i] == "")
{
fieldData[i] = null;
}
}
csvData.Rows.Add(fieldData);
}
}
}
catch (Exception ex)
{
}
return csvData;
}
示例9: 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;
}
}
示例10: LoadCSVToDataSet
public static IMLDataSet LoadCSVToDataSet(FileInfo fileInfo, int inputCount, int outputCount, bool randomize = true, bool headers = true)
{
BasicMLDataSet result = new BasicMLDataSet();
CultureInfo CSVformat = new CultureInfo("en");
using (TextFieldParser parser = new TextFieldParser(fileInfo.FullName))
{
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
if (headers)
parser.ReadFields();
while (!parser.EndOfData)
{
//Processing row
string[] fields = parser.ReadFields();
var input = new BasicMLData(inputCount);
for (int i = 0; i < inputCount; i++)
input[i] = double.Parse(fields[i], CSVformat);
var ideal = new BasicMLData(outputCount);
for (int i = 0; i < outputCount; i++)
ideal[i] = double.Parse(fields[i + inputCount], CSVformat);
result.Add(input, ideal);
}
}
var rand = new Random(DateTime.Now.Millisecond);
return (randomize ? new BasicMLDataSet(result.OrderBy(r => rand.Next()).ToList()) : new BasicMLDataSet(result));
}
示例11: GetStock
public Stock GetStock(StockName stockName, DateTime startDate, DateTime endDate)
{
string dir = String.Format(@"..\..\StockData\Maya");
string filename = String.Format("{0}.csv", stockName);
var fullPath = Path.Combine(dir, filename);
var rates = new List<IStockEntry>();
var parser = new TextFieldParser(fullPath) {TextFieldType = FieldType.Delimited};
parser.SetDelimiters(",");
//skips the first 3 lines
parser.ReadFields();
parser.ReadFields();
parser.ReadFields();
while (!parser.EndOfData)
{
var fields = parser.ReadFields();
if (fields != null)
{
StockEntry stockEntry = null;
rates.Add(stockEntry);
}
}
rates.Reverse();
var stock = new Stock(stockName, rates);
return stock;
}
示例12: GetDataTabletFromCSVFile
public DataTable GetDataTabletFromCSVFile(string csv_file_path, string service)
{
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);
}
while (!csvReader.EndOfData)
{
string[] fieldData = csvReader.ReadFields();
for (int i = 0; i < fieldData.Length; i++)
{
if (fieldData[i] == "")
{
fieldData[i] = null;
}
else
{
switch (service)
{
case "email":
fieldData[i] = this.RemoveSpecialCharactersEmail(fieldData[i]);
break;
case "deduplicate":
fieldData[i] = this.RemoveSpecialCharactersDeduplicate(fieldData[i]);
break;
default:
fieldData[i] = this.RemoveSpecialCharacters(fieldData[i]);
break;
}
}
}
csvData.Rows.Add(fieldData);
}
}
}
catch (Exception ex)
{
//TO DO
}
return csvData;
}
示例13: ImportCSV
public static void ImportCSV(string file)
{
TextFieldParser parser = new TextFieldParser(file);
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
Boolean header = true;
while (!parser.EndOfData)
{
// We don't want to import the header row
if (header)
{
header = false;
parser.ReadFields();
continue;
}
// Vars
DateTime dt;
DateTime dt2 = Convert.ToDateTime("4/15/2010");
Boolean error = false;
string[] fields = parser.ReadFields();
// Check for error conditions
if (String.IsNullOrEmpty(fields[3]))
{
// Score is null
fields[3] = "0";
error = true;
}
if (!DateTime.TryParse(fields[2], out dt))
{
// Date is invalid
fields[2] = "05/05/55";
error = true;
}
if (dt > dt2)
{
// Date is > 4/15/2010
error = true;
}
// Insert into the correct table
if (error)
{
InsertError(fields[0], fields[1], fields[2], fields[3]);
}
else
{
Insert(fields[0], fields[1], fields[2], fields[3]);
}
}
parser.Close();
}
示例14: CsvReader
/// <summary>
/// CSVを読み込みます。
/// </summary>
/// <param name="path">読み込みディレクトリパス</param>
/// <param name="filename">読み込みファイル名</param>
/// <returns>読み込んだCSVをDataTableで返却</returns>
public DataTable CsvReader(string path, string filename)
{
string[] data;
DataTable dt = new DataTable();
TextFieldParser parser = new TextFieldParser(path + filename, encord);
parser.TextFieldType = FieldType.Delimited;
// 区切り文字はコンマ
parser.SetDelimiters(",");
//データがあるか確認します。
if (!parser.EndOfData)
{
//CSVファイルから1行読み取ります。
data = parser.ReadFields();
//カラムの数を取得します。
int cols = data.Length;
try
{
for (int i = 0; i < cols; i++)
{
//カラム名をセットします
dt.Columns.Add(data[i]);
}
}
catch (System.Data.DuplicateNameException)
{
MessageBox.Show( "読み込みエラー\nチェックリストの中に重複している値がないか確認し、修正を行ってから実行しなおしてください。" );
//DataTable aa = new DataTable();
//return aa;
}
}
// CSVをデータテーブルに格納
while (!parser.EndOfData)
{
data = parser.ReadFields();
DataRow row = dt.NewRow();
for (int i = 0; i < dt.Columns.Count; i++)
{
row[i] = data[i];
}
dt.Rows.Add(row);
}
parser.Dispose();
return dt;
}
示例15: btnParseTextFiles_Click
private void btnParseTextFiles_Click(object sender, EventArgs e)
{
using (TextFieldParser myReader = new TextFieldParser("test.txt"))
{
// 定义三种格式之各栏的宽度与分隔字符。
int[] FirstFormat = { 5, 10, -1 };
int[] SecondFormat = { 6, 10, 17, -1 };
string[] ThirdFormat = { "," };
this.DataGridView1.Rows.Clear();
this.DataGridView2.Rows.Clear();
this.DataGridView3.Rows.Clear();
string[] CurrentRow;
while (!myReader.EndOfData)
{
try
{
string RowType = myReader.PeekChars(2);
switch (RowType)
{
case "CK":
myReader.TextFieldType = FieldType.FixedWidth;
myReader.FieldWidths = FirstFormat; // 或是 myReader.SetFieldWidths(FirstFormat);
CurrentRow = myReader.ReadFields();
this.DataGridView1.Rows.Add(CurrentRow);
break;
case "PB":
myReader.TextFieldType = FieldType.FixedWidth;
myReader.FieldWidths = SecondFormat; // 或是 myReader.SetFieldWidths(SecondFormat);
CurrentRow = myReader.ReadFields();
this.DataGridView2.Rows.Add(CurrentRow);
break;
case "SP":
myReader.TextFieldType = FieldType.Delimited;
myReader.Delimiters = ThirdFormat; // 或是 myReader.SetDelimiters(ThirdFormat);
CurrentRow = myReader.ReadFields();
this.DataGridView3.Rows.Add(CurrentRow);
break;
}
}
catch (MalformedLineException ex)
{
MessageBox.Show("行 " + ex.Message + " 是无效的。略过。");
}
}
// 排序各个 DataGridView 控件的内容。
DataGridView1.Sort(DataGridView1.Columns[0], System.ComponentModel.ListSortDirection.Ascending);
DataGridView2.Sort(DataGridView2.Columns[0], System.ComponentModel.ListSortDirection.Ascending);
DataGridView3.Sort(DataGridView3.Columns[0], System.ComponentModel.ListSortDirection.Ascending);
}
}