开发者

Read a file from a resource and write it to disk in C#

I have some files, which are embedded in a resource. How can I save these files on disk v开发者_如何学Cia C#?


This should do your job:

        string strTempFile = Path.GetTempFileName();
        File.WriteAllBytes(strTempFile, Properties.Resources.YourBinaryFileInResource);

Be sure, that the FileType of the included files is set to "binary".


using streams: GetManifestResourceStream gives you a stream to the file in the resource and using a StreamWriter you can write the contents of that stream to disk.


You can get the resource stream, then read from the stream while writing to the file.

        byte[] buffer = new byte[1024];
        using (Stream output = File.OpenWrite("filename"))
        {
            using (Stream resourceStream = typeof(Class1).Assembly.GetManifestResourceStream("name of resource"))
            {
                int bytes = -1;
                while ((bytes = resourceStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    output.Write(buffer, 0, bytes);
                }
            }
        }

Code is completely untested, just to give you an idea.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜