是的,那是因为 ASCII 只有 7 位 - 它没有定义任何高于 127 的值。编码通常将未知的二进制值解码为“?” (虽然这可以使用DecoderFallback 更改)。
如果您要提及“扩展 ASCII”,我怀疑您实际上想要 Encoding.Default,它是“操作系统的默认代码页”...code page 1252 在大多数西方系统上,我相信。
你期待什么角色?
编辑:根据接受的答案(我怀疑在我添加答案后对问题进行了编辑;我不记得最初看到任何关于 JPEG 的内容)您不应该将二进制数据转换为文本,除非它是真正编码的文本数据。 JPEG 数据是 二进制 数据 - 因此您应该检查实际字节与预期字节。
只要您使用“纯”文本编码(例如 ASCII、UTF-8 等)将任意二进制数据(例如图像、音乐或视频)转换为文本,您就有数据丢失的风险。如果您有 将其转换为文本,请使用既美观又安全的 Base64。但是,如果您只想将其与预期的二进制数据进行比较,最好不要将其转换为文本。
编辑:好的,这是一个帮助给定字节数组的图像检测方法的类。我还没有让它特定于 HTTP。我不完全确定您是否真的应该获取InputStream,只读一点,然后再次获取流。我通过坚持字节数组来回避这个问题:)
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
public sealed class SignatureDetector
{
public static readonly SignatureDetector Png =
new SignatureDetector(0x89, 0x50, 0x4e, 0x47);
public static readonly SignatureDetector Bmp =
new SignatureDetector(0x42, 0x4d);
public static readonly SignatureDetector Gif =
new SignatureDetector(0x47, 0x49, 0x46);
public static readonly SignatureDetector Jpeg =
new SignatureDetector(0xff, 0xd8);
public static readonly IEnumerable<SignatureDetector> Images =
new ReadOnlyCollection<SignatureDetector>(new[]{Png, Bmp, Gif, Jpeg});
private readonly byte[] bytes;
public SignatureDetector(params byte[] bytes)
{
if (bytes == null)
{
throw new ArgumentNullException("bytes");
}
this.bytes = (byte[]) bytes.Clone();
}
public bool Matches(byte[] data)
{
if (data == null)
{
throw new ArgumentNullException("data");
}
if (data.Length < bytes.Length)
{
return false;
}
for (int i=0; i < bytes.Length; i++)
{
if (data[i] != bytes[i])
{
return false;
}
}
return true;
}
// Convenience method
public static bool IsImage(byte[] data)
{
return Images.Any(detector => detector.Matches(data));
}
}