111,126
社区成员
发帖
与我相关
我的任务
分享
public class FileMap
{
public List<byte[]> list = null;
public void Test(string path)
{
list = new List<byte[]>();
...
long fileOffset = 0;
long fileSize = 0;
uint blockBytes = 64<<20;//64M
while (fileSize > 0)
{
IntPtr lpbMapAddress = MapViewOfFile(mappingFileHandle, FILE_MAP_COPY | FILE_MAP_READ,(uint)(fileOffset >> 32), (uint)(fileOffset & 0xFFFFFFFF),blockBytes);
byte[] temp = new byte[blockBytes];
// 代码1,Program 类中 for 循环输出结果(最初1K字节)正确
Marshal.Copy(lpbMapAddress, temp, 0, (int)blockBytes);
list.Add(temp);
// end:代码1
// 代码2,Program 类中 for 循环输出结果(最初1K字节)错误,但是代码2中 if(i==0) 时,结果正确;而改 if(i==1) 时,结果同 Program 类中 for 循环,错误
byte[] tmp = new byte[1024];
for(int i = 0; i < temp.Length; i+=1024)
{
Array.Clear(tmp,0,tmp.Length);
Buffer.BlockCopy(temp, i, tmp, 0, 1024);
//输出最初1K字节
if(i==0)// i==0:正确;i==1:错误
{
for(int j = 0; j < 1024; j++)
{
Console.Write(tmp[j].ToString("X2")+",");
}
}
list.Add(tmp);
}
// end:代码2
UnmapViewOfFile(lpbMapAddress);
fileOffset += blockBytes;
fileSize -= blockBytes;
}
}
}
public class Program
{
static void Main(string[] args)
{
FileMap fileMap = new FileMap();
fileMap.Test(@"test.rar");//文件大小:8388608B = 8M
Console.WriteLine(fileMap.list.Count.ToString());// 结果正确,代码1结果为:1,代码2结果为:8192
byte[] temp = (byte[])(fileMap.list[0]);
for(int i = 0; i < 1024; i++)
{
Console.Write(temp[i].ToString("X2")+",");
}
}
}
/// <summary>
/// 返回基地址某偏移处的字节。
/// </summary>
/// <param name="source">基地址</param>
/// <param name="offset">偏移量</param>
/// <returns>字节</returns>
public static byte PointerToByte(IntPtr source, int offset)
{
unsafe
{
byte* pbyte = (byte*)source.ToPointer();
pbyte += offset;
return *pbyte;
}
}
/// <summary>
/// 从基地址某偏移处填充给定大小的字节数组
/// </summary>
/// <param name="source">基地址</param>
/// <param name="offset">偏移量</param>
/// <param name="destination">目标数组</param>
public static void FillBytesFromPointer(IntPtr source, int offset, byte[] destination)
{
unsafe
{
byte* pbyte = (byte*)source.ToPointer();
pbyte += offset;
for (int i = 0; i < destination.Length; i++)
{
destination[i] = *pbyte;
pbyte++;
}
}
}
IntPtr lpbMapAddress = MapViewOfFile(mappingFileHandle, FILE_MAP_COPY | FILE_MAP_READ,(uint)(fileOffset >> 32), (uint)(fileOffset & 0xFFFFFFFF),blockBytes);
for(int i = 0; i < blockBytes; i+=1024)
{
byte[] tmp = new byte[1024];
FillBytesFromPointer(lpbMapAddress, i, tmp);
//输出最初1K字节
if(i==0)
{
for(int j = 0; j < 1024; j++)
{
Console.Write(tmp[j].ToString("X2")+",");
}
}
list.Add(tmp);
}
for(int i = 0; i < temp.Length; i+=1024)
{
byte[] tmp = new byte[1024];
Buffer.BlockCopy(temp, i, tmp, 0, 1024);
if(i==0)
{
for(int j = 0; j < 1024; j++)
{
Console.Write(tmp[j].ToString("X2")+",");
}
}
list.Add(tmp);
}
if(i==0)// i==0:正确;i==1:错误
{
for(int j = 0; j < 1024; j++)
{
Console.Write(tmp[j].ToString("X2")+",");
}
}
for(int i=0;i<fileMap.list.Count;i++)
{
for(int j=0;j<fileMap.list[i].Length;j+=1024)
{
stream.Seek(j,SeekOrigin.Begin);
stream.Write(fileMap.list[i], j, 1024);
}
}