none
Search Exact word using linq c# RRS feed

  • Question

  • Hi All,

        I have a notepad with several section, the format as show below(notepad content):-

    [SECTION]

    SITETYPE = "08/10/2012 01:00:08"

    [SECTION1]

    TYPE = "0.01"

    I need to fetch "0.01" value from the "TYPE". I am using the below list to read those values in the file.

    List<string> listOfFile;
    List<object> ctlFileInfo = new List<object>();
    listOfFile = Directory.GetFiles(Directorypath, "*.txt").ToList();
                        if (listOfFile != null && listOfFile.Count > 0)
                        {
                            listOfFile.ForEach(ctlfile =>
                            {
                                File.ReadAllLines(ctlfile).ToList().ForEach(line =>
                                {
                                    if (line.Contains("TYPE"))
                                    {
                                        FileInfo fileinfo = new FileInfo(ctlfile);
                                        if (!string.IsNullOrEmpty(fileinfo.Name.Remove(fileinfo.Name.Length - 4)))
                                            ctlFileInfo.Add(new
                                            {
                                                fileName = fileinfo.Name,
                                                typeNumber = line.Substring(line.LastIndexOf('=') + 1),                                          
                                                sectionName = fileinfo.Name.Substring(0, fileinfo.Name.LastIndexOf('.'))
                                            });
                                    }
                                });
                            });

    My issue is it is taking SITETYPE value rather than taking TYPE value, since it has "Contains" keyword it is taking SITETYPE then TYPE value, so two duplicate values are occurring, I need only one value from TYPE, I have used "==", "Equals", nothing is working. Yet to try Regex.ismatch.  Any idea's to fix this issue? Thanks in Advance.

    Tuesday, April 9, 2019 6:40 PM

Answers

  • Hi Viorel,

      ‘if(line.TrimLeft().StartsWith(“TYPE”)) --> its not working,

    I tried Regular expression as below which is working

    if (Regex.IsMatch(line, string.Format(@"\b{0}\b", Regex.Escape("TYPE")))

    Thanks

    Tuesday, April 9, 2019 9:24 PM

All replies

  • Have you also tried ‘if(line.TrimLeft().StartsWith(“TYPE”))’?

    Regular Expressions are probably more appropriate.


    • Edited by Viorel_MVP Tuesday, April 9, 2019 7:12 PM
    Tuesday, April 9, 2019 7:11 PM
  • Hi Viorel,

      ‘if(line.TrimLeft().StartsWith(“TYPE”)) --> its not working,

    I tried Regular expression as below which is working

    if (Regex.IsMatch(line, string.Format(@"\b{0}\b", Regex.Escape("TYPE")))

    Thanks

    Tuesday, April 9, 2019 9:24 PM