【问题标题】:Read and process a remote zipped xml file in C#在 C# 中读取和处理远程压缩的 xml 文件
【发布时间】:2020-05-26 22:28:42
【问题描述】:

在 C# 中读取和处理远程压缩 xml 文件的正确方法是什么?

这是我的尝试:

private Task UpdateLegalContractors(string url)
{
    url = @"https://srv-file7.gofile.io/download/k67HY4/sampleOpenData.zip";

    string res = string.Empty;

    using (var file = File.OpenRead(url))
    using (var zip = new ZipArchive(file, ZipArchiveMode.Read))
    {
        foreach (var entry in zip.Entries)
        {
            using (var stream = entry.Open())
            using (var reader = XmlReader.Create(stream))
            {
                while (reader.Read())
                {
                    switch (reader.NodeType)
                    {
                        case XmlNodeType.Element:
                            res += reader.Name;
                            break;
                        case XmlNodeType.XmlDeclaration:
                            res += "<?xml version=\"1.0\" encoding=\"windows - 1251\"?>";
                            break;
                    }
                }
            }
        }
    }

    var stop = 0;

    return null;
}

this 问题中提出了解决方案。

对我来说,一旦到达using (var file = File.OpenRead(url)) 行,解决方案就会出错。错误说明如下:

{"不支持给定路径的格式。"}

我应该改变什么才能使解决方案起作用?

【问题讨论】:

    标签: c# xml download stream zip


    【解决方案1】:

    问题在这里:https://srv-file7.gofile.io/download/k67HY4/sampleOpenData.zipFile 类仅适用于本地文件。首先,您必须将此文件下载到本地存储,然后打开它。 例如,使用来自 answer 的解决方案。

    直接内存解决方案:

    WebClient wc = new WebClient();
    using (MemoryStream stream = new MemoryStream(wc.DownloadData("URL")))
    {
        using (var zip = new ZipArchive(stream, ZipArchiveMode.Read))
        {
           ...
        }
    }
    

    【讨论】:

    • 非常感谢您的时间和关注。但这不是我要找的。我不想将文件存储在磁盘上,我想在内存中处理它。除了使用File 类,还有其他方法吗?
    • 文件 calss 无法从 https 读取。您不能保存临时文件并在处理后将其删除?
    • 在这个问题的范围内,我不考虑将文件保留在磁盘上。
    • @hellouworld 我用内存处理完成了我的答案。从头开始写,因此可能需要修复。
    猜你喜欢
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-24
    • 2011-10-04
    相关资源
    最近更新 更多