开发者

managed c++ .NET extract file from resource, wrong file size

Hi im trying to extract a file from my embedded resource but the issue is that the file size is not correct, it should be around 3500KB but it comes out as 5850KB or so.

            Assembly ^myAssembly = Assembly::GetExecutingAssembly();
        Stream ^myStream = myAssembly->GetManifestResourceStream("cool.exe");
        FileStream^ fs = gcnew FileStream("cool.exe",FileMode::Append,FileAccess::Write,FileShar开发者_如何学Ce::Write);
        StreamReader^ Reader = gcnew StreamReader(myStream);
        StreamWriter^ Writer = gcnew StreamWriter(fs);
        Writer->Write(Reader->ReadToEnd());
        fs->Close();

This is the edited one:

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 
        }

Then to use it:

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();

This will make the correct file and correct file size =)


Binary data isn't text.

The StreamReader is converting your data to UTF8, which isn't what you want.
You need to copy the raw bytes by calling Write and Read.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜