使用 .net 和 C# 从 sftp 下载 zip 文件时出现错误

问题描述 投票:0回答:1

我正在尝试使用 SshNet 访问 sftp 文件夹,然后访问位于该处的 zip 文件中的内容。我遇到以下异常:

System.IO.InvalidDataException: 'Central Directory corrupt'
Inner Exception
     EndOfStreamException: Unable to read beyond the end of the stream

这是我正在使用的功能:

public string GetContents(string filename, ref string error)
{
    string contents = "";
    using (var sftp = new SftpClient(SFTP_URI, SFTP_USERNAME, SFTP_PASSWORD))
    {
        try
        {
            sftp.Connect();
        }
        catch (Exception exc)
        {
            error = "Unable to connect " + SFTP_USERNAME + "@" + SFTP_URI + " - " + exc.Message;
            return contents;
        }

        if (!sftp.Exists(filename))
        {
            error = "Filename doesn't exist - " + filename;
            return contents;
        }

        using (Stream stream = sftp.OpenRead(filename))
        {
            using (var archive = new ZipArchive(stream, ZipArchiveMode.Read, true)) //exception thrown here
            {
                foreach (var files in archive.Entries) //just using this block for testing to see if I can access the zip folder
                {
                    Console.WriteLine(files);
                }
            }
        }
    }
    return contents;
}
c# .net ziparchive ssh.net
1个回答
0
投票

Chris Schaller 的评论让我想到首先将该 zip 目录读入 MemoryStream 对象,然后将其传递给 ZipArchive 构造函数。成功了!

public string GetContents(string filename, ref string error)
{
    string contents = "";
    using (var sftp = new SftpClient(SFTP_URI, SFTP_USERNAME, SFTP_PASSWORD))
    {
        try
        {
            sftp.Connect();
        }
        catch (Exception exc)
        {
            error = "Unable to connect " + SFTP_USERNAME + "@" + SFTP_URI + " - " + exc.Message;
            return contents;
        }

        if (!sftp.Exists(filename))
        {
            error = "Filename doesn't exist - " + filename;
            return contents;
        }


        using (MemoryStream ms = new MemoryStream())
        {
            try
            {
                sftp.DownloadFile(filename, ms);
                using (var archive = new ZipArchive(ms, ZipArchiveMode.Read, true))
                {
                    foreach (var files in archive.Entries)
                    {
                        Console.WriteLine(files);
                    }
                }
            }
            catch (Exception exc)
            {
                error = "Exception downloading " + filename + " - " + exc.Message;
                return contents;
            }
        }
    }
    return contents;
}
© www.soinside.com 2019 - 2024. All rights reserved.