开发者

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 dir开发者_如何学运维ectory. Could you please give me some samples for it?

Thanks SuT


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))


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜