How to get all the files with a specific extension from a directory using LINQ with WinForms and C#

1 Answer

0 votes
namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
    public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string[] dir = Directory.GetFiles("d:\\Test");

            var files = dir.Select(file => new FileInfo(file).FullName);
            string filelist = "";

            foreach (string element in files)
            {
                string extension = element.Substring(element.IndexOf("."));
                
                if (extension == ".txt")
                {
                    filelist += element + Environment.NewLine;
                }
            }

            MessageBox.Show(filelist);
        }
    }
}




/*
run:

d:\\Test\\data.txt
d:\\Test\\numbers.txt
d:\\Test\\VPN.txt
 
*/

 



answered Apr 22, 2024 by avibootz
...