如何使用C#重命名.rar .7z,.tar,.zip中的文件和文件夹

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

我有一个压缩文件.rar .7z,.tar和.zip,我想重命名上面使用C#压缩的压缩文件中可用的物理文件名。

[我已经使用Sharpcompress库进行了尝试,但是在.rar .7z,.tar和.zip文件中找不到重命名文件或文件夹名称的功能。

我也尝试过使用DotNetZip库,但是它唯一的支持。请参阅我使用DotNetZip库所尝试的内容。

private static void RenameZipEntries(string file)
        {
            try
            {
                int renameCount = 0;
                using (ZipFile zip2 = ZipFile.Read(file))
                {

                    foreach (ZipEntry e in zip2.ToList())
                    {
                        if (!e.IsDirectory)
                        {
                            if (e.FileName.EndsWith(".txt"))
                            {
                                var newname = e.FileName.Split('.')[0] + "_new." + e.FileName.Split('.')[1];
                                e.FileName = newname;
                                e.Comment = "renamed";
                                zip2.Save();
                                renameCount++;
                            }
                        }
                    }
                    zip2.Comment = String.Format("This archive has been modified. {0} files have been renamed.", renameCount);
                    zip2.Save();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

但是实际上我也想要.7z,.rar和.tar,与上面相同,我尝试了许多库,但仍然没有任何准确的解决方案。

请帮助我。

c# zip tar 7zip rar
1个回答
0
投票

考虑7zipsharp:

https://www.nuget.org/packages/SevenZipSharp.Net45/

7zip本身支持许多存档格式(我相信您提到的所有内容),而7zipsharp使用真正的7zip。我只将7zipsharp用于.7z文件,但我敢打赌它对其他人也有用。

这里是一个测试示例,似乎使用ModifyArchive方法重命名了文件,建议您在其中上学:

https://github.com/squid-box/SevenZipSharp/blob/f2bee350e997b0f4b1258dff520f36409198f006/SevenZip.Tests/SevenZipCompressorTests.cs

这是简化的代码。请注意,该测试会压缩7z文件进行测试;这无关紧要,可能是.txt等。还请注意,它通过传递给ModifyArchive的词典中的索引来查找文件。有关如何从文件名获取索引的信息,请查阅文档(也许您必须循环比较)。

        var compressor = new SevenZipCompressor( ... snip ...);

        compressor.CompressFiles("tmp.7z", @"Testdata\7z_LZMA2.7z");

        compressor.ModifyArchive("tmp.7z", new Dictionary<int, string> { { 0, "renamed.7z" }});

        using (var extractor = new SevenZipExtractor("tmp.7z"))
        {
            Assert.AreEqual(1, extractor.FilesCount);
            extractor.ExtractArchive(OutputDirectory);
        }

        Assert.IsTrue(File.Exists(Path.Combine(OutputDirectory, "renamed.7z")));
        Assert.IsFalse(File.Exists(Path.Combine(OutputDirectory, "7z_LZMA2.7z")));
© www.soinside.com 2019 - 2024. All rights reserved.