我正在尝试使用 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;
}
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;
}