首页 > 学院 > 开发设计 > 正文

[C#]ExtractEmbeddedResourceToFile

2019-11-14 16:27:50
字体:
来源:转载
供稿:网友

关键代码:

        /// <summary>        /// 将嵌入的资源写入到本地        /// </summary>        /// <param name="resourceName">嵌入的资源名称</param>        /// <param name="filename">写入本地的路径</param>        /// <returns>是否成功</returns>        public static bool ExtractEmbeddedResourceToFile(string resourceName, string filename)        {            bool _result = false;            try            {                Assembly _curCall = Assembly.GetCallingAssembly();                string _curCallAssemblyName = _curCall.GetName(false).Name;                resourceName = string.Format("{0}.{1}", _curCallAssemblyName, resourceName);                using (Stream stream = _curCall.GetManifestResourceStream(resourceName))                {                    if (stream != null)                    {                        using (FileStream fs = new FileStream(filename, FileMode.Create))                        {                            byte[] _byte = new byte[stream.Length];                            stream.Read(_byte, 0, _byte.Length);                            fs.Write(_byte, 0, _byte.Length);                            _result = true;                        }                    }                }            }            catch (Exception ex)            {                _result = false;                Debug.WriteLine(string.Format("ExtractEmbeddedResourceToFile Exception:{0}", ex.Message));            }            return _result;        }

测试代码:

1.将文件设置成嵌入成资源

image

2.编写代码:

CSharpToolV2.ExtractEmbeddedResourceToFile("cat.jpg", @"C:/cat.jpg");

希望有所帮助!


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表