C# 判断以rar、zip、7z为扩展名的压缩文件是否损坏,不使用引用包System.IO.Compression
时间: 2024-02-05 22:11:18 浏览: 178
可以使用以下代码判断以rar、zip、7z为扩展名的压缩文件是否损坏:
```csharp
using System;
using System.IO;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
string filePath = "example.rar"; // 压缩文件路径
string extension = Path.GetExtension(filePath)?.ToLower(); // 获取文件扩展名并转换为小写
bool isCorrupted = false; // 是否损坏
switch (extension)
{
case ".rar":
isCorrupted = IsRarCorrupted(filePath);
break;
case ".zip":
isCorrupted = IsZipCorrupted(filePath);
break;
case ".7z":
isCorrupted = Is7zCorrupted(filePath);
break;
default:
Console.WriteLine("不支持的文件格式");
break;
}
if (isCorrupted)
{
Console.WriteLine("文件损坏");
}
else
{
Console.WriteLine("文件正常");
}
Console.ReadKey();
}
// 判断rar文件是否损坏
static bool IsRarCorrupted(string filePath)
{
using (var stream = new FileStream(filePath, FileMode.Open))
{
var header = new byte[7];
while (stream.Read(header, 0, 7) > 0)
{
if (header[0] == 0x52 && header[1] == 0x61 && header[2] == 0x72 && header[3] == 0x21 &&
header[4] == 0x1a && header[5] == 0x07 && (header[6] == 0x00 || header[6] == 0x01))
{
return false;
}
else
{
var size = BitConverter.ToInt16(header, 5);
stream.Seek(size, SeekOrigin.Current);
}
}
}
return true;
}
// 判断zip文件是否损坏
static bool IsZipCorrupted(string filePath)
{
using (var stream = new FileStream(filePath, FileMode.Open))
{
var buffer = new byte[22];
if (stream.Read(buffer, 0, 22) < 22)
{
return true;
}
if (BitConverter.ToUInt32(buffer, 0) != 0x04034b50)
{
return true;
}
var fileNameLength = BitConverter.ToUInt16(buffer, 26);
var extraFieldLength = BitConverter.ToUInt16(buffer, 28);
stream.Seek(fileNameLength + extraFieldLength, SeekOrigin.Current);
return false;
}
}
// 判断7z文件是否损坏
static bool Is7zCorrupted(string filePath)
{
using (var stream = new FileStream(filePath, FileMode.Open))
{
var buffer = new byte[6];
if (stream.Read(buffer, 0, 6) < 6)
{
return true;
}
var signature = BitConverter.ToUInt64(buffer, 0);
if (signature != 0x377abcaf271c)
{
return true;
}
var headerSize = BitConverter.ToUInt16(buffer, 4);
stream.Seek(headerSize, SeekOrigin.Current);
return false;
}
}
}
}
```
注意:以上代码只能判断是否损坏,无法确定文件是否能够正常解压缩。
阅读全文