GZipStream抱怨标题中的魔术数字不正确

joc*_*ull 6 .net c# gzip gzipstream

我正在尝试使用国家气象局(US)数据,但最近发生了一些变化,GZip文件不再打开。

.NET 4.5抱怨...

Message=The magic number in GZip header is not correct. Make sure you are passing in a GZip stream.
Source=System
StackTrace:
   at System.IO.Compression.GZipDecoder.ReadHeader(InputBuffer input)
   at System.IO.Compression.Inflater.Decode()
   at System.IO.Compression.Inflater.Inflate(Byte[] bytes, Int32 offset, Int32 length)
   at System.IO.Compression.DeflateStream.Read(Byte[] array, Int32 offset, Int32 count)
Run Code Online (Sandbox Code Playgroud)

我不知道发生了什么变化,但这已成为一个真正的秀场停止者。有GZip格式经验的人可以告诉我为使此停止工作进行了哪些更改吗?

有效的文件:

http://www.srh.noaa.gov/ridge2/Precip/qpehourlyshape/2015/201504/20150404/nws_precip_2015040420.tar.gz

无效的文件:

http://www.srh.noaa.gov/ridge2/Precip/qpehourlyshape/2015/201505/20150505/nws_precip_2015050505.tar.gz

用示例代码更新

const string url = "http://www.srh.noaa.gov/ridge2/Precip/qpehourlyshape/2015/201505/20150505/nws_precip_2015050505.tar.gz";
string appPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string downloadPath = Path.Combine(appPath, Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "nws_precip_2015050505.tar.gz");
using (var wc = new WebClient())
{
    wc.DownloadFile(url, downloadPath);
}

string extractDirPath = Path.Combine(appPath, "Extracted");
if (!Directory.Exists(extractDirPath))
{
    Directory.CreateDirectory(extractDirPath);
}
string extractFilePath = Path.Combine(extractDirPath, "nws_precip_2015050505.tar");

using (var fsIn = new FileStream(downloadPath, FileMode.Open, FileAccess.Read))
using (var fsOut = new FileStream(extractFilePath, FileMode.Create, FileAccess.Write))
using (var gz = new GZipStream(fsIn, CompressionMode.Decompress, true))
{
    gz.CopyTo(fsOut);
}
Run Code Online (Sandbox Code Playgroud)

joc*_*ull 6

似乎此服务SOMETIMES返回tar伪装为的格式文件.tar.gz。这非常令人困惑,但是如果您检查前两个字节是0x1F0x8B,则可以通过手动检查其魔术数来检测该文件是否为GZip。

using (FileStream fs = new FileStream(downloadPath, FileMode.Open, FileAccess.Read))
{
    byte[] buffer = new byte[2];
    fs.Read(buffer, 0, buffer.Length);
    if (buffer[0] == 0x1F
        && buffer[1] == 0x8B)
    {
        // It's probably a GZip file
    }
    else
    {
        // It's probably not a GZip file
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 碉堡了。这些愚蠢的 qpe 文件给我带来了一些严重的麻烦。此消息应标记为“错误 GZIP 标头,第一个幻数字节不匹配”和“GZip 标头中的幻数不正确。确保您传递的是 GZip 流。” 非常感谢您解决这个问题! (2认同)