[英]How to Rename Files and Folder in .rar .7z, .tar, .zip using C#
I have a compressed file .rar .7z, .tar and .zip and I want to rename physical file name available in above compressed archived using C#.我有一个压缩文件 .rar .7z、.tar 和 .zip,我想重命名上面使用 C# 存档的压缩文件中可用的物理文件名。
I have tried this using a sharpcompress library but I can't find such a feature for rename file or folder name within .rar .7z, .tar and .zip file.我已经使用一个sharpcompress 库尝试过这个,但是我在.rar .7z、.tar 和.zip 文件中找不到这样的重命名文件或文件夹名称的功能。
I also have tried using the DotNetZip library but its only support.Zip see what I have tried using DotNetZip library.我也尝试过使用 DotNetZip 库,但它唯一的支持。 Zip 看看我使用 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());
}
}
But actually the same as above I also want for .7z, .rar and .tar, I tried many libraries but still I didn't get any accurate solution.但实际上和上面一样,我也想要 .7z、.rar 和 .tar,我尝试了很多库,但仍然没有得到任何准确的解决方案。
Please help me.请帮我。
Consider 7zipsharp:考虑 7zipsharp:
https://www.nuget.org/packages/SevenZipSharp.Net45/ https://www.nuget.org/packages/SevenZipSharp.Net45/
7zip itself supports lots of archive formats (I believe all you mentioned) and 7zipsharp uses the real 7zip. 7zip 本身支持许多存档格式(我相信你提到的所有内容),而 7zipsharp 使用真正的 7zip。 I've used 7zipsharp for .7z files only but I bet it works for others.
我只将 7zipsharp 用于 .7z 文件,但我敢打赌它适用于其他人。
Here's a sample of a test that appears to rename a file using ModifyArchive method, I suggest you go to school in it:这是一个使用 ModifyArchive 方法重命名文件的测试示例,我建议您在其中上学:
https://github.com/squid-box/SevenZipSharp/blob/f2bee350e997b0f4b1258dff520f36409198f006/SevenZip.Tests/SevenZipCompressorTests.cs https://github.com/squid-box/SevenZipSharp/blob/f2bee350e997b0f4b1258dff520f36409198f006/SevenZip.Tests/SevenZipCompressorTests.cs
Here's the code simplified a bit.这是稍微简化的代码。 Note that the test compresses a 7z file for its test;
请注意,该测试压缩了一个 7z 文件以进行测试; that's immaterial it could be .txt, etc. Also note it finds the file by index in the dictionary passed to ModifyArchive.
这无关紧要,它可能是 .txt 等。另请注意,它通过传递给 ModifyArchive 的字典中的索引查找文件。 Consult documentation for how to get that index from a filename (maybe you have to loop and compare).
请参阅文档以了解如何从文件名中获取该索引(也许您必须循环比较)。
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")));
This is a simple console application to rename files in .zip这是一个简单的控制台应用程序,用于重命名 .zip 文件
using System;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
namespace Renamer
{
class Program
{
static void Main(string[] args)
{
using var archive = new ZipArchive(File.Open(@"<Your File>.zip", FileMode.Open, FileAccess.ReadWrite), ZipArchiveMode.Update);
var entries = archive.Entries.ToArray();
//foreach (ZipArchiveEntry entry in entries)
//{
// //If ZipArchiveEntry is a directory it will have its FullName property ending with "/" (e.g. "some_dir/")
// //and its Name property will be empty string ("").
// if (!string.IsNullOrEmpty(entry.Name))
// {
// var newEntry = archive.CreateEntry($"{entry.FullName.Replace(entry.Name, $"{RandomString(10, false)}{Path.GetExtension(entry.Name)}")}");
// using (var a = entry.Open())
// using (var b = newEntry.Open())
// a.CopyTo(b);
// entry.Delete();
// }
//}
Parallel.ForEach(entries, entry =>
{
//If ZipArchiveEntry is a directory it will have its FullName property ending with "/" (e.g. "some_dir/")
//and its Name property will be empty string ("").
if (!string.IsNullOrEmpty(entry.Name))
{
ZipArchiveEntry newEntry = archive.CreateEntry($"{entry.FullName.Replace(entry.Name, $"{RandomString(10, false)}{Path.GetExtension(entry.Name)}")}");
using (var a = entry.Open())
using (var b = newEntry.Open())
a.CopyTo(b);
entry.Delete();
}
});
}
//To Generate random name for the file
public static string RandomString(int size, bool lowerCase)
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
if (lowerCase)
return builder.ToString().ToLower();
return builder.ToString();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.