gpt4 book ai didi

c# - 托管 C++ .NET 从资源中提取文件,文件大小错误

转载 作者:行者123 更新时间:2023-11-30 04:33:28 25 4
gpt4 key购买 nike

您好,我正在尝试从我的嵌入式资源中提取文件,但问题是文件大小不正确,它应该在 3500KB 左右,但结果是 5850KB 左右。

            Assembly ^myAssembly = Assembly::GetExecutingAssembly();
Stream ^myStream = myAssembly->GetManifestResourceStream("cool.exe");
FileStream^ fs = gcnew FileStream("cool.exe",FileMode::Append,FileAccess::Write,FileShare::Write);
StreamReader^ Reader = gcnew StreamReader(myStream);
StreamWriter^ Writer = gcnew StreamWriter(fs);
Writer->Write(Reader->ReadToEnd());
fs->Close();

这是编辑后的:

Assembly ^myAssembly = Assembly::GetExecutingAssembly();
Stream ^myStream = myAssembly->GetManifestResourceStream("cool.exe");
FileStream^ fs = gcnew FileStream("cool.exe",FileMode::Append,FileAccess::Write,FileShare::Write);
StreamReader^ Reader = gcnew StreamReader(myStream);
StreamWriter^ Writer = gcnew StreamWriter(fs);
//Writer->Write(Reader->ReadToEnd());

array<Byte^>^ buffer = gcnew array<Byte^>(256);

while (true)
{

int read = Reader->Read(buffer,0,buffer->Length);
if(read <= 0)
{
return;
}
Writer->Write(buffer,0,read);
}

fs->Close();

解决方案

public: static void CopyStream(Stream^ input, Stream^ output) 
{

array<Byte>^ buffer = gcnew array<Byte>(32768);

long TempPos = input->Position;

while (true)
{
int read = input->Read(buffer, 0, buffer->Length);
if (read <= 0) break;
output->Write (buffer, 0, read);
}
input->Position = TempPos;// or you make Position = 0 to set it at the start
}

然后使用它:

Assembly ^myAssembly = Assembly::GetExecutingAssembly();
Stream ^myStream = myAssembly->GetManifestResourceStream("cool.exe");
FileStream^ fs = gcnew FileStream("cool.exe",FileMode::Append,FileAccess::Write,FileShare::Write);

CopyStream(myStream,fs);
fs->Close();

这将生成正确的文件和正确的文件大小 =)

最佳答案

二进制数据不是文本。

StreamReader 正在将您的数据转换为 UTF8,这不是您想要的。
您需要通过调用 WriteRead 来复制原始字节。

关于c# - 托管 C++ .NET 从资源中提取文件,文件大小错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6808073/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com