【发布时间】:2015-10-01 15:09:48
【问题描述】:
在我的函数 GetAssemblyResourceStream(下面的代码)中,我使用“assembly.GetManifestResourceStream”和“resourceReader.GetResourceData”从 Dll 读取资源。
当我从资源的字节数组中设置我的内存流时,我必须包含 4 个字节的偏移量:
const int OFFSET = 4;
resStream = new MemoryStream(data, OFFSET, data.Length - OFFSET);
这个偏移的原因是什么?它是从哪里来的?
参考:MSDN ResourceReader Class 末尾的示例
另外:我制作了一个测试应用来更好地了解资源。该应用程序显示了我在偏移方面遇到的问题。我的小测试应用程序可在Github (VS 2015)
2015-10-05 10h28 更新由于答案非常低,我怀疑存在错误和/或未记录的行为。我在Connect.Microsoft.com 报告了一个错误,并会看到结果。
2015-10-07 更新我删除了这个错误。我仍然认为它没有得到很好的记录和/或可能被视为一个错误,但我高度怀疑他们会在不做任何事情的情况下关闭我的请求。我希望没有人会遇到和我一样的问题。
代码:
// ******************************************************************
/// <summary>
/// The path separator is '/'. The path should not start with '/'.
/// </summary>
/// <param name="asm"></param>
/// <param name="path"></param>
/// <returns></returns>
public static Stream GetAssemblyResourceStream(Assembly asm, string path)
{
// Just to be sure
if (path[0] == '/')
{
path = path.Substring(1);
}
// Just to be sure
if (path.IndexOf('\\') == -1)
{
path = path.Replace('\\', '/');
}
Stream resStream = null;
string resName = asm.GetName().Name + ".g.resources"; // Ref: Thomas Levesque Answer at:
// http://stackoverflow.com/questions/2517407/enumerating-net-assembly-resources-at-runtime
using (var stream = asm.GetManifestResourceStream(resName))
{
using (var resReader = new System.Resources.ResourceReader(stream))
{
string dataType = null;
byte[] data = null;
try
{
resReader.GetResourceData(path.ToLower(), out dataType, out data);
}
catch (Exception ex)
{
DebugPrintResources(resReader);
}
if (data != null)
{
switch (dataType) // COde from
{
// Handle internally serialized string data (ResourceTypeCode members).
case "ResourceTypeCode.String":
BinaryReader reader = new BinaryReader(new MemoryStream(data));
string binData = reader.ReadString();
Console.WriteLine(" Recreated Value: {0}", binData);
break;
case "ResourceTypeCode.Int32":
Console.WriteLine(" Recreated Value: {0}", BitConverter.ToInt32(data, 0));
break;
case "ResourceTypeCode.Boolean":
Console.WriteLine(" Recreated Value: {0}", BitConverter.ToBoolean(data, 0));
break;
// .jpeg image stored as a stream.
case "ResourceTypeCode.Stream":
////const int OFFSET = 4;
////int size = BitConverter.ToInt32(data, 0);
////Bitmap value1 = new Bitmap(new MemoryStream(data, OFFSET, size));
////Console.WriteLine(" Recreated Value: {0}", value1);
const int OFFSET = 4;
resStream = new MemoryStream(data, OFFSET, data.Length - OFFSET);
break;
// Our only other type is DateTimeTZI.
default:
////// No point in deserializing data if the type is unavailable.
////if (dataType.Contains("DateTimeTZI") && loaded)
////{
//// BinaryFormatter binFmt = new BinaryFormatter();
//// object value2 = binFmt.Deserialize(new MemoryStream(data));
//// Console.WriteLine(" Recreated Value: {0}", value2);
////}
////break;
break;
}
// resStream = new MemoryStream(resData);
}
}
}
return resStream;
}
【问题讨论】:
标签: c# character-encoding stream resources offset