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

时间:2011-07-24 16:27:05

标签: c# .net c++ managed

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

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

1 个答案:

答案 0 :(得分:2)

二进制数据不是文本。

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