如何在C#中1个1个地加载目录中的文件?

发布于 2024-12-01 00:28:09 字数 72 浏览 2 评论 0原文

我想使用 C# 1 1 加载所有 xml 文件。并且所有文件都位于同一目录下。 你能给我一些样品吗?

谢谢 苏特

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

熊抱啵儿 2024-12-08 00:28:09

只需凭记忆输入此内容,但我相信这会起作用:

DirectoryInfo di = new DirectoryInfo(PathToYourFolder);

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

如果您确实需要进入子文件夹,请进行以下更改:

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

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))
心碎无痕… 2024-12-08 00:28:09

我不确定你所说的“1 by 1”是什么意思,但我想这就是你正在寻找的。

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();
        }
    }
}

xmlsmyPath 中的所有文件,也是所有子文件夹中的文件,通过 SearchOption 您可以定义是否需要所有文件或仅顶级文件。接下来,对每个找到的文件打开一个文件流,并使用流读取器来读取整个内容。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文