从资源文件到计算机保存图像 - C# [英] Save image from resource file to computer - c#

查看:103
本文介绍了从资源文件到计算机保存图像 - C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Okei,我有一个资源文件C#项目。
中的资源文件包含一个图片(.png)。
我想保存/提取到我的计算机上的指定文件夹PNG文件。
我如何做到这一点?


解决方案

 静态无效ExtractFileResource(字符串RESOURCE_NAME ,串FILE_NAME)
{

{
如果(File.Exists(FILE_NAME))
File.Delete(FILE_NAME);

如果
Directory.CreateDirectory(Path.GetDirectoryName(FILE_NAME))(Directory.Exists(Path.GetDirectoryName(FILE_NAME))!);使用

(流sfile = Assembly.GetExecutingAssembly()GetManifestResourceStream(RESOURCE_NAME)。)
{
的byte [] buf中=新的字节[sfile.Length]
sfile.Read(BUF,0,Convert.ToInt32(sfile.Length));使用

(的FileStream FS = File.Create(FILE_NAME))
{
fs.Write(BUF,0,Convert.ToInt32(sfile.Length));
fs.Close();
}
}
}
赶上(异常前)
{
抛出新的异常(的String.Format(不能提取资源{0 }到文件{1}:{2},RESOURCE_NAME,FILE_NAME,ex.Message),前);
}
}


Okei, I have a C# project with a resource file. The resource file contains a image (.png). I want the png file to be saved/extracted to a specified folder on my computer. How do I do this?

解决方案

    static void ExtractFileResource(string resource_name, string file_name)
    {
        try
        {
            if (File.Exists(file_name))
                File.Delete(file_name);

            if (!Directory.Exists(Path.GetDirectoryName(file_name)))
                Directory.CreateDirectory(Path.GetDirectoryName(file_name));

            using (Stream sfile = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource_name))
            {
                byte[] buf = new byte[sfile.Length];
                sfile.Read(buf, 0, Convert.ToInt32(sfile.Length));

                using (FileStream fs = File.Create(file_name))
                {
                    fs.Write(buf, 0, Convert.ToInt32(sfile.Length));
                    fs.Close();
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception(string.Format("Can't extract resource '{0}' to file '{1}': {2}", resource_name, file_name, ex.Message), ex);
        }
    }

这篇关于从资源文件到计算机保存图像 - C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆