Search code examples
c#xmllistfolderbrowserdialog

How to select only XML files from selected folder in C#?


I want add add all xml files of a selected folder in to a list in C#. Following code works fine if all files are only xml.

I want to filter xml files if there are any other files in same folder.

Is it possible to select only xml files using my existing code ?

Thank you

FolderBrowserDialog folderDlg = new FolderBrowserDialog();
DialogResult result = folderDlg.ShowDialog();

if (result == DialogResult.OK)
{
    string[] files = Directory.GetFiles(folderDlg.SelectedPath);

    lblFolder.Text = "Folder : " + folderDlg.SelectedPath;
    lblFiles.Text = "No of Xml Found : " + files.Length.ToString();

    try
    {
        foreach (string filePath in files)
        {
            xmlFilePath.Add(filePath);

        }

        foreach (string file in files)
        {
            string fileName =Path.GetFileNameWithoutExtension(file);
            Version.Add(fileName);
        }

    }
    catch (System.Exception ex)
    {
        lbl_notifications.Text = ex.Message;
    }
}

Solution

  • GetFiles method accepts optional parameter as searchpattern (*search string to match against the names of files in path).

    Provide .xml filter in your case as follows to get only xml files from the directory.

    string[] files = Directory.GetFiles(folderDlg.SelectedPath, "*.xml");