当前位置: 首页>>代码示例>>C#>>正文


C# TextFieldParser.ReadFields方法代码示例

本文整理汇总了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++;
                }
            }
        }
开发者ID:FrankNine,项目名称:Heartache,代码行数:25,代码来源:ExtraStrg.cs

示例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);
        }
开发者ID:kebabdk,项目名称:FileConverters,代码行数:29,代码来源:XtrainerDataProvider.cs

示例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();
        }
开发者ID:robgray,项目名称:Tucana,代码行数:33,代码来源:Program.cs

示例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);
            }
              }
        }
开发者ID:Taras-Tyrsa,项目名称:CsvToEntitiesParser,代码行数:41,代码来源:CsvParser.cs

示例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));
                }
            }
        }
开发者ID:sboulema,项目名称:codeassignment1,代码行数:36,代码来源:OVTransactionImport.cs

示例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();
        }
开发者ID:Art1stical,项目名称:AHRUnrealEngine,代码行数:33,代码来源:ReportFile.cs

示例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;
        }
开发者ID:RoyNing,项目名称:CSVExtracter,代码行数:31,代码来源:Program.cs

示例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;
 }
开发者ID:nonconforme,项目名称:UrhoAngelscriptIDE,代码行数:40,代码来源:DataTableBuilder.cs

示例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;
            }
        }
开发者ID:1andy,项目名称:plcdev,代码行数:25,代码来源:CsvReader.cs

示例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));
        }
开发者ID:JGrzybowski,项目名称:NeuralNetworksSmallProject,代码行数:28,代码来源:CSVHelper.cs

示例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;
        }
开发者ID:ilan84,项目名称:ZulZula,代码行数:32,代码来源:MayaDataProvider.cs

示例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;
        }
开发者ID:mpwebstudio,项目名称:dataCleansing,代码行数:58,代码来源:CsvToDataTable.cs

示例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();
        }
开发者ID:vgck,项目名称:archive,代码行数:53,代码来源:Program.cs

示例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;
        }
开发者ID:youmjww,项目名称:exerciseCheck,代码行数:58,代码来源:Csv.cs

示例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);
     }
 }
开发者ID:TGHGH,项目名称:C-1200,代码行数:50,代码来源:Form1.cs


注:本文中的Microsoft.VisualBasic.FileIO.TextFieldParser.ReadFields方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。