简体   繁体   English

从SQL Server获取zip文件列表

[英]Get list of zip file from SQL Server

I have a table in a SQL Server database with a varbinary(max) column with zip archives. 我在SQL Server数据库中有一个带有zip存档的varbinary(max)列的表。 How do I get a list of these archives without extracting them? 我如何获取这些档案的列表而不提取它们? My C# application reads the list of these archives, and I need to add more information about the content. 我的C#应用​​程序读取这些档案的列表,我需要添加有关内容的更多信息。

For file I use the ZipFile class from System.IO.Compression.FileSystem assembly, but how to pass varbinary data instead file name (if I create CLR Function, for example)? 对于文件,我使用System.IO.Compression.FileSystem程序ZipFile类,但是如何传递varbinary数据而不是文件名(例如,如果我创建CLR Function)?

Is this what you are looking for? 这是你想要的?

SQLCLR C# function... SQLCLR C#函数...

using System.Data.SqlTypes;
using System.IO;
using System.IO.Compression;
using System.Linq;

public partial class UserDefinedFunctions
{
    [Microsoft.SqlServer.Server.SqlFunction]
    public static SqlString ZipEntries(SqlBytes data) {
        using (var stream = new MemoryStream(data.Value))
        using (var archive = new ZipArchive(stream))
            return new SqlString(string.Join(",", archive.Entries.Select(e => e.Name)));
    }
}

Here's the SQL I used to test. 这是我用来测试的SQL。 Surprisingly, it worked ... 令人惊讶的是,它起作用了...

-- Create table with ZIP archive column...
CREATE TABLE dbo.ZipImages(ZipArchive VARBINARY(MAX));
GO

-- ... then insert ZIP archive content into the dbo.ZipImages table ...
-- (code not included)
GO

-- ... then prove it works.
SELECT dbo.ZipEntries(ZipArchive) FROM dbo.ZipImages;
GO

It is possible/probable that your database will whine about System.IO.Compression not being available, in which case you can try ... 您的数据库可能/很可能会抱怨System.IO.Compression不可用,在这种情况下,您可以尝试...

ALTER DATABASE [<your database>] SET TRUSTWORTHY ON;

CREATE ASSEMBLY [System.IO.Compression]
FROM N'C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.IO.Compression.dll'
WITH PERMISSION_SET = EXTERNAL_ACCESS;

(If you're not the DBA, you'll want to make friends quickly.) (如果您不是DBA,则希望快速结交朋友。)

This is just a bare-bones UDF, obviously -- you probably want to do something a bit different (like make it a table-based CLR UDF to return the entries one-by-one). 显然,这只是一个简单的UDF-您可能想做一些不同的事情(例如使它成为基于表的CLR UDF以逐项返回条目)。

If you need to open files from the archive in the data column, it gets trickier. 如果您需要从数据列中的存档中打开文件,它将变得更加棘手。 Among other things, you will have to add System.IO.Compression.File as an assembly, which is (unfortunately) UNSAFE and complicates a bunch of things... 除其他事项外,您将必须将System.IO.Compression.File作为程序集添加,(不幸的是)UNSAFE并使一堆事情变得复杂...

CREATE ASSEMBLY [System.IO.Compression.FileSystem]
FROM N'C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.IO.Compression.FileSystem.dll'
WITH PERMISSION_SET = UNSAFE;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM