• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# FileIO.TextFieldParser类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中Microsoft.VisualBasic.FileIO.TextFieldParser的典型用法代码示例。如果您正苦于以下问题:C# TextFieldParser类的具体用法?C# TextFieldParser怎么用?C# TextFieldParser使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



TextFieldParser类属于Microsoft.VisualBasic.FileIO命名空间,在下文中一共展示了TextFieldParser类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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;
        }
开发者ID:mpwebstudio,项目名称:dataCleansing,代码行数:30,代码来源:CsvToDataTable.cs


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


示例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[] { "," };
 }
开发者ID:NumAniCloud,项目名称:BattlePrompt,代码行数:7,代码来源:CsvReader.cs


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


示例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));
            }
        }
开发者ID:sea1jxr,项目名称:LeMondCsvToTCX,代码行数:34,代码来源:LeMondGForceSTNCsvDataProvider.cs


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


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


示例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;
 }
开发者ID:chaoskie,项目名称:LP,代码行数:35,代码来源:CSVReader.cs


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


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


示例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)
        };
    }
}
            
        }
开发者ID:harpagornis,项目名称:coding.abel.nu,代码行数:25,代码来源:BrandReader.cs


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


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


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


示例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);
            }
        }
开发者ID:kits-kroon,项目名称:ViberToPDF,代码行数:25,代码来源:Implementation.cs


示例16: ParseCharacterFromTranslationCsv

        private static void ParseCharacterFromTranslationCsv(string translationCSVPath,
                                                             Dictionary<string, HashSet<char>> customFontCharacterSets)
        {
            using (TextFieldParser parser = new TextFieldParser(translationCSVPath))
            {
                parser.TextFieldType = FieldType.Delimited;
                parser.SetDelimiters(",");
                parser.ReadFields(); // Skip header

                while (!parser.EndOfData)
                {
                    string[] fields = parser.ReadFields();

                    string translatedString = fields[csvTranslatedStringCol];
                    string translationFont = fields[csvFontIdCol];

                    if (!string.IsNullOrEmpty(translatedString))
                    {
                        foreach (char c in translatedString.ToCharArray())
                        {
                            customFontCharacterSets[translationFont].Add(c);
                        }
                    }
                }
            }
        }
开发者ID:FrankNine,项目名称:Heartache,代码行数:26,代码来源:GlyphInjector.cs


示例17: ReadAll

        //Read the newline sepearted pair first and last names
        public IList<NameModel> ReadAll(string filePath)
        {
            IList<NameModel> users = null;
            if (File.Exists(filePath))
            {
                using (var reader = File.OpenRead(filePath))
                using (var textFileParser = new TextFieldParser(reader))
                {
                    textFileParser.TrimWhiteSpace = true;
                    textFileParser.Delimiters = new[] {","};
                    while (!textFileParser.EndOfData)
                    {
                        //Read comma sepearted line
                        var line = textFileParser.ReadFields();
                        //Create mapped model for each row of data

                        var name = GetNameModel(line);
                        if (name != null)
                        {
                            if (users == null) users = new List<NameModel>();
                            users.Add(name);
                        }
                    }
                }
            }
            return users;
        }
开发者ID:vijayaneeraj,项目名称:Name-Sorter,代码行数:28,代码来源:TextFileReaderWritter.cs


示例18: GetDataFromCSVStream

        public Task<string[][]> GetDataFromCSVStream()
        {
            List<string[]> result = new List<string[]>();
            TaskCompletionSource<string[][]> resultTask = new TaskCompletionSource<string[][]>();
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(connectionURL);
                req.GetResponseAsync().ContinueWith(
                    (task) =>
                    {
                        WebResponse resp = task.Result;
                        using (TextFieldParser parser = new TextFieldParser(resp.GetResponseStream()))
                        {
                            parser.Delimiters = new string[] { "," };
                            while (true)
                            {
                                string[] line = parser.ReadFields();
                                if (line == null)
                                    break;
                                result.Add(line);
                            }
                        }
                        resultTask.SetResult(result.ToArray());
                    }
                );

            }
            catch (Exception e)
            {
                result.Add(new string[] { e.Message });
            }
            return resultTask.Task;
        }
开发者ID:chenyuzhcy,项目名称:stock-analysis-addin,代码行数:33,代码来源:WebData.cs


示例19: 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


示例20: 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;
 }
开发者ID:bmcc91,项目名称:Testing-WithDeletes,代码行数:32,代码来源:Duplicates.xaml.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# VisualStudio.VSConstants类代码示例发布时间:2022-05-26
下一篇:
C# VisualBasic.VBCodeProvider类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap