1

I have code which looks for .ini files in all folders in root directory. I want to show only folder those .ini files are in, that is only info relevant to me, because it shows different project names. But as far I can figure it out I can only show full path to file or only file itself in listbox. Any help? My code:

    private void Form1_Load(object sender, EventArgs e)
    {
        string rootdir = @"C:\Users\isaced1\Desktop\test";   //root directory of all projects
        string[] files = Directory.GetFiles(rootdir, "Project_config.ini", SearchOption.AllDirectories);  //searches for specific .ini files in all directories whithin rood directory
                                                                                             //cycles through all .ini files and adds it to lsitbox1 or listbox2
        foreach (string item in files)
        {
            string fileContents = File.ReadAllText(item); //reads all .ini files
            const string PATTERN = @"OTPM = true"; //search pattern in .ini files
            Match match = Regex.Match(fileContents, PATTERN, RegexOptions.IgnoreCase); //matches pattern with content in .ini file
            if (match.Success)
            {
                listBox1.Items.Add(Path.GetDirectoryName(item)); //if match is successfull places file in lisbox1
                listBox1.ForeColor = Color.Green;
            }
            else
            {
                listBox2.Items.Add(Path.GetDirectoryName(item)); //if match is unsuccessfull places file in lisbox2
                listBox2.ForeColor = Color.Red;
            }
        }
    }
burgund
  • 357
  • 1
  • 5
  • 12
Katonas
  • 39
  • 3
  • 1
    what is wrong with `Path.GetDirectoryName` ? or do you need only the directory name ? – Mong Zhu Oct 04 '22 at 08:32
  • it gets entire full path whit out a file name, and way to long – Katonas Oct 04 '22 at 09:05
  • 1
    Bind the box (`.DataSource = ..`) to an instance of `List`, set `.DisplayMember = "Name"` and `.ValueMember = "FullName"`. Note, `.ForeColor = ...` sets the control's foreground color used to draw all the items. You need to set `.DrawMode = DrawMode.OwnerDrawFixed;` and handle the `DrawItem` event to draw the items with different colors. The `ListView` control is good alternative here, you can set the fore/back colors, font ...etc. per item. – dr.null Oct 04 '22 at 09:55
  • i am a bit new to c# so i dont really understand those comands – Katonas Oct 04 '22 at 10:06
  • then the real question is: "how to get only the directory name from file name?" – Mong Zhu Oct 04 '22 at 12:01

1 Answers1

0
listBox1.Items.Add(new Uri(Path.GetDirectoryName(item)).Segments.Last())

This one worked perfectly!

Katonas
  • 39
  • 3