SUT
SUT

Reputation: 404

How could I load the files of a directory 1 by 1 in C#?

I want to load all xml files 1 by 1 by using C#. And all files are under same directory. Could you please give me some samples for it?

Thanks SuT

Upvotes: 1

Views: 116

Answers (2)

dowhilefor
dowhilefor

Reputation: 11051

i'm not sure what you mean with "1 by 1" but i guess this is what you are looking for.

var xmls = Directory.GetFiles(myPath, "*.xml", SearchOption.AllDirectories);
foreach (var file in xmls )
{
    using (var fileStream = new FileStream(file, FileMode.Open))
    {
        using (var reader = new StreamReader(fileStream))
        {
            reader.BaseStream.Seek(0, SeekOrigin.Begin);
            fileContent = reader.ReadToEnd();
        }
    }
}

xmls are all files in myPath and also inside all subfolders via SearchOption you can define if you want all files or only TopLevel files. Next a fileStream is openend for eaech of the found files and a stream reader is used to read the whole content.

Upvotes: 2

Russ Clarke
Russ Clarke

Reputation: 17909

Just typing this from memory, but this would do the trick I believe:

DirectoryInfo di = new DirectoryInfo(PathToYourFolder);

foreach (FileInfo fi in di.GetFiles("*.xml")) 
{
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(fi.FullName);
}

If you do need to go into child folders then make this change:

foreach (FileInfo fi in di.GetFiles("*.xml", SearchOption.AllDirectories))

Upvotes: 9

Related Questions