I have the following method that validates if certain file exist in the a zipped file. The method might get a zipped file or not from IFormFile.
private static bool FileExistsInZip(IFormFile uploadedFile, string fileName)
{
using ZipArchive archive = new ZipArchive(uploadedFile.OpenReadStream(), ZipArchiveMode.Read);
return archive.Entries.Any(entry => entry.Name.Equals(fileName, StringComparison.OrdinalIgnoreCase));
}
So in the above method, uploaded file could be zip file or just text file or an image. I was wondering if ZipArchive will return false in this case but it throws ArgumentOutOfRange exception when trying to open file type that is not in Zip format. For example a 4 byte txt file.
What would be the right approach to handle this kind of scenario ?
CodePudding user response:
The typical solution when there is an exception is to catch it and handle it somehow.
However, if you want to test if a file is a zip file you can instead check the header. For zip files this should be 0x04034b50
. So something like:
using var br = new BinaryReader(uploadedFile.OpenReadStream());
if(br.ReadUint32 == 0x04034b50){
//is zip file
}
This will only check if the header has the correct magic numbers, it will not tell if the actual file is corrupted, for that you might need to read the entire file, including any entries, and catch any exception that occur. If you want to know the specific file type there are lists of magic numbers for different file formats.