【问题标题】:Could not zip folder because of symbolic link由于符号链接,无法压缩文件夹
【发布时间】:2022-08-11 16:33:14
【问题描述】:

我正在尝试克隆一个包含符号链接的 git 存储库,然后使用以下代码对其进行 ZIP(压缩):

public Stream Compress(string folder)
{
    try
    {
        var tempFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
        ZipFile.CreateFromDirectory(folder, tempFile, CompressionLevel.Optimal, false);
        return new Stream(tempFile);
    }
    catch (Exception e)
    {
        // handle exception
        ...
    }
}

但是由于符号链接,我有以下例外:

System.IO.FileNotFoundException:找不到文件\'/tmp/2a765552-c60d-4ff8-b915-54e3d049902f/environment/bin/python3\'。

有没有办法忽视或者解决符号链接?

  • 您使用的是什么 zip 实用程序?查看文档以了解如何处理符号链接。有很多 ZIP 实用程序,但并非都相同。
  • @jdweng 我正在使用 ZipFile 类。 docs.microsoft.com/en-us/dotnet/api/…
  • 看起来 ZipFile 没有办法避免异常。在左侧的同一链接中,有 ZipArchive 和 ZipArchiveEntry,可用于一次添加一个文件以进行归档。

标签: c# .net-core zip symlink system.io.compression


【解决方案1】:

我能够使用以下逻辑将符号链接添加到一个一个处理文件的包中:

    FileInfo fi = new(filePath);
    if (fi.LinkTarget == null) {
        var entry = archive.CreateEntryFromFile(filePath, entryName);
    }
    else
    {
        // handle symbolic links
        var entry = archive.CreateEntry(entryName);
        using (var entryStream = entry.Open())
        using (var streamWriter = new StreamWriter(entryStream))
        {
            streamWriter.Write(fi.LinkTarget);
        }
        // write posix attributes manually
        entry.ExternalAttributes = (int)fi.Attributes | ((S_IFLNK | S_IRWXU | S_IRWXG | S_IRWXO) << 17);
    }

其中archiveZipArchive 对象,filePath 是要添加到具有条目名称entryName 的包的文件的文件路径

    const int S_IFLNK = 0120000;
    const int S_IRWXU = 0000700;
    const int S_IRWXG = 0000070;
    const int S_IRWXO = 0000007;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-14
    • 1970-01-01
    • 1970-01-01
    • 2017-08-15
    • 2017-04-18
    • 1970-01-01
    • 2012-01-23
    • 2011-11-30
    相关资源
    最近更新 更多