列出位于C#中SFTP服务器上的ZIP文件中的文件 [英] List files inside ZIP file located on SFTP server in C#
问题描述
我需要通过ASP.NET Core以编程方式处理SFTP服务器(WinSCP)的ZIP文件中的文件夹.
I need to process folders inside a ZIP file from SFTP server (WinSCP) programmatically through ASP.NET Core.
有什么方法可以获取ZIP文件中的文件列表,而无需下载到本地计算机?作为文件大小会很高,并且不会保持一致.任何帮助将不胜感激.
Is there any way where I can get list of files inside ZIP file without downloading to local computer? As the file size would be high and won't be in a consistent manner. Any help would be appreciated.
推荐答案
使用 SSH.NET库,它可能像这样简单:
With SSH.NET library, it could be as easy as:
using (var client = new SftpClient(host, username, password)
{
client.Connect();
using (Stream stream = client.OpenRead("/remote/path/archive.zip"))
using (var archive = new ZipArchive(stream, ZipArchiveMode.Read))
{
foreach (var entry in archive.Entries)
{
Console.WriteLine(entry);
}
}
}
您需要引用 System.IO.Compression
程序集以获取
You need to reference System.IO.Compression
assembly to get the ZipArchive
.
该代码将仅读取(下载)ZIP中央目录记录,而不是整个ZIP存档.
The code will only read (download) the ZIP central directory record, not whole ZIP archive.
不幸的是,该库中存在一个错误.要解决此问题,您必须像这样实现包装器 Stream
的实现:
Unfortunately, there's a bug in the library. To workaround it, you have to implement a wrapper Stream
implementation like this:
class FixStream : Stream
{
public override long Seek(long offset, SeekOrigin origin)
{
long result;
// workaround for SSH.NET bug in implementation of SeekOrigin.End
if (origin == SeekOrigin.End)
{
result = _stream.Seek(Length + offset, SeekOrigin.Begin);
}
else
{
result = _stream.Seek(offset, origin);
}
return result;
}
// passthrough implementation of the rest of Stream interface
public override bool CanRead => _stream.CanRead;
public override bool CanSeek => _stream.CanSeek;
public override bool CanWrite => _stream.CanWrite;
public override long Length => _stream.Length;
public override long Position {
get => _stream.Position; set => _stream.Position = value; }
public FixStream(Stream stream)
{
_stream = stream;
}
public override void Flush()
{
_stream.Flush();
}
public override int Read(byte[] buffer, int offset, int count)
{
return _stream.Read(buffer, offset, count);
}
public override void SetLength(long value)
{
_stream.SetLength(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
_stream.Write(buffer, offset, count);
}
private Stream _stream;
}
并将 SftpFileStream
包裹到其中:
using (Stream stream = client.OpenRead("/remote/path/archive.zip"))
using (var stream2 = new FixStream(stream))
using (var archive = new ZipArchive(stream2, ZipArchiveMode.Read))
{
...
}
这篇关于列出位于C#中SFTP服务器上的ZIP文件中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!