从资源中提取文件,文件大小错误



嗨,我试图从我嵌入的资源中提取一个文件,但问题是文件大小不正确,它应该在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();

SOLOUTION

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来复制原始字节。

相关内容

  • 没有找到相关文章

最新更新