本文整理汇总了C#中Microsoft.VisualBasic.FileIO.TextFieldParser.SetDelimiters方法的典型用法代码示例。如果您正苦于以下问题:C# TextFieldParser.SetDelimiters方法的具体用法?C# TextFieldParser.SetDelimiters怎么用?C# TextFieldParser.SetDelimiters使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.VisualBasic.FileIO.TextFieldParser
的用法示例。
在下文中一共展示了TextFieldParser.SetDelimiters方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: btnConvert_Click
private void btnConvert_Click(object sender, EventArgs e)
{
if (_salary == null)
{
return;
}
_salary.Header = null;
_salary.Rows.Clear();
using (Stream stream = GenerateStreamFromString(_salary.RawText))
{
TextFieldParser parser = new TextFieldParser(stream);
parser.HasFieldsEnclosedInQuotes = true;
parser.SetDelimiters(",");
string[] fields;
int counter = 0;
while (!parser.EndOfData)
{
fields = parser.ReadFields();
if (fields == null || fields.Length == 0)
continue;
if (counter == 0)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < fields.Length; i++)
{
string field = fields[i].Trim().Replace(" ", "").Replace(" ", "").Replace("\n", "").Replace("\r", "");
field = field.Replace("\"", "\"\"");
if (i != fields.Length - 1)
{
sb.AppendFormat("\"{0}\",", field);
}
else
{
sb.AppendFormat("\"{0}\"", field);
}
}
_salary.Header = sb.ToString();
counter++;
}
else
{
string name = fields[0].Trim().Replace(" ", "").Replace(" ", "").Replace("\n", "");
if (name.StartsWith("\"") && name.EndsWith("\""))
{
}
else
{
name = "\"" + name.Replace("\"", "\"\"") + "\"";
}
fields[0] = name;
_salary.Rows.Add(string.Join(",", fields));
}
}
}
Render();
btnSave.Enabled = true;
}
示例2: 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++;
}
}
}
示例3: read
// ファイル入力
// readFileName:入力先のファイル名
// return:行ごとの情報を保持するリスト
public static List<String[]> read(String readFileName)
{
// 読み込んできた行を保持するインスタンス
List<String[]> readLines = new List<String[]>();
try
{
// テキストを読み込むためのインスタンス
TextFieldParser parser = new TextFieldParser(readFileName);
// 分割される状態をセット
parser.TextFieldType = FieldType.Delimited;
// 区切り文字の設定
parser.SetDelimiters(",");
// ファイルの終端まで処理
while (!parser.EndOfData)
{
String[] row = parser.ReadFields(); // 1行読み込み
readLines.Add(row); // 行を保持
}
}
catch (Exception e)
{
MessageBox.Show("" + e, "error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
return readLines;
}
示例4: 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;
}
示例5: 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;
}
示例6: BuildRecords
public static List<ForexRecord> BuildRecords()
{
var dataFile = ConfigurationManager.AppSettings["TestDataDirectory"] + "\\ForexTrading.csv";
var records = new List<ForexRecord>();
using (var parser = new TextFieldParser(dataFile))
{
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
while (!parser.EndOfData)
{
var fields = parser.ReadFields();
if (fields == null)
{
continue;
}
records.Add(new ForexRecord
{
CurrencyPair = fields[0],
Date = fields[1],
Bid = double.Parse(fields[2]),
Ask = double.Parse(fields[3])
});
}
}
return records;
}
示例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: 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));
}
示例9: 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);
}
}
}
示例10: 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;
}
示例11: 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;
}
示例12: 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;
}
示例13: 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);
}
}
示例14: Continue_Click
private void Continue_Click(object sender, RoutedEventArgs e)
{
continueButton.IsEnabled = false;
bool flag = false;
string[] lastDTS = {""};
dupeListBox.Items.Clear();
string[] dtsList = File.ReadAllLines(DTSListSuite.App.mDtsListFile);
foreach (string line in dtsList)
{
if (line.Substring(0, 3) != "C/R")
{
TextFieldParser parser = new TextFieldParser(new StringReader(line));
parser.HasFieldsEnclosedInQuotes = true;
parser.SetDelimiters(",");
string[] ArLn = { "" };
while (!parser.EndOfData)
ArLn = parser.ReadFields();
if (lastDTS.Length > 1)
{
if (ArLn[1] == lastDTS[1] && ArLn[2] == lastDTS[2] && ArLn[3] == lastDTS[3])
{
dupeListBox.Items.Insert(0, ArLn[1] + " " + ArLn[2] + " " + ArLn[3] + "\tDuplicate!");
flag = true;
}
}
lastDTS = ArLn;
}
}
if (!flag)
dupeListBox.Items.Insert(0, "No Duplicates!");
continueButton.IsEnabled = true;
}
示例15: Go
public void Go()
{
var inputPath = IO.GetInputFilePath("TextFieldParseRegex.txt");
var line = new string('=', 40);
Console.WriteLine(line);
using (var parser = new TextFieldParser(inputPath))
{
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(";");
parser.TrimWhiteSpace = true;
parser.HasFieldsEnclosedInQuotes = true;
while (parser.PeekChars(1) != null)
{
Console.WriteLine("Line {0}: ", parser.LineNumber);
var cleanFieldRowCells = parser.ReadFields().Select(
f => f.Trim(new[] { ' ', '"' })).ToArray();
for (int i = 0; i < cleanFieldRowCells.Length; ++i)
{
Console.WriteLine(
"Field[{0}] = [{1}]", i, cleanFieldRowCells[i]
);
}
Console.WriteLine(line);
}
}
}