I’m trying to convert rar to zip using system.io.compression.
I’m getting "System.IO.InvalidDataException: ‘End of Central Directory record could not be found.’" with 0 byte zip file.
I have no idea why.
string fname = Path.GetFileNameWithoutExtension(rarf);
string path = Path.GetDirectoryName(rarf);
string newfpath = Path.Combine(path, fname) + ".zip";
using (var zFS = new FileStream(newfpath, FileMode.CreateNew))//zip
{
using (var zip = new ZipArchive(zFS, ZipArchiveMode.Create, true))
{
using (var rarFS = File.OpenRead(rarf))//rar
{
using (var rar = new ZipArchive(rarFS, ZipArchiveMode.Read))
{
foreach (ZipArchiveEntry RARentry in rar.Entries)
{
using (var RARms = RARentry.Open())
{
var zipArchiveEntry = Zip.CreateEntry(RARentry.FullName, CompressionLevel.Fastest);
using (var ZIPms = zipArchiveEntry.Open())
{
RARms.Seek(0, SeekOrigin.Begin);
RARms.CopyTo(ZIPms);
}
}
}
}
}
}
}
As advised, I used sharpcompress and modified the code as following and it works! Thank you.
using (var zFS = new FileStream(newfpath, FileMode.CreateNew))//zip
{
using (var zip = new ZipArchive(zFS, ZipArchiveMode.Create, true))
{
using (var rar = RarArchive.Open(rarf))
{
foreach (var RARentry in rar.Entries)
{
if (!RARentry.IsDirectory)
{
var RARms = new MemoryStream();
RARentry.WriteTo(RARms);
var zipArchiveEntry = zip.CreateEntry(RARentry.Key, System.IO.Compression.CompressionLevel.Fastest);
using (var ZIPms = zipArchiveEntry.Open())
{
RARms.Seek(0, SeekOrigin.Begin);
RARms.CopyTo(ZIPms);
}
}
}
}
}
}
>Solution :
You are trying to open a RAR archive using ZipArchive. The ZipArchive class in System.IO.Compression is specifically designed to work with ZIP archives, not RAR archives.
RAR and ZIP are different compression formats, and they are not interchangeable
The error you are encountering, "End of Central Directory record could
not be found," suggests that the ZIP library is unable to find the
necessary metadata that indicates the end of the ZIP archive.
Unfortunately, the .NET Framework’s System.IO.Compression does not include native support for RAR archives.
You might want to consider using a third-party library that supports RAR, such as SharpCompress, which is a compression library for .NET that supports various formats, including RAR.
Usage:
using (var archive = RarArchive.Open(rarf))
{
foreach (var entry in archive.Entries)
{
entry.WriteToDirectory(path, new ExtractionOptions()
{
ExtractFullPath = true,
Overwrite = true
});
}
}
Note : Make sure to add a reference to the SharpCompress library to your project.