Reputation: 201
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;
}
}
Upvotes: 0
Views: 2985
Reputation: 16956
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");
Upvotes: 4
Reputation: 6251
The Directory.GetFiles()
function has an overload which accepts filters for the type of files to include in the search, so you can easily use "*.xml"
to search for only XML
files:
string[] files = Directory.GetFiles(folderDlg.SelectedPath, "*.xml");
Upvotes: 3