制作应用安装程序时从Resources复制PNG文件至本地文件夹报错求助
解决从My.Resources复制PNG/TXT到本地文件夹的问题
嘿,我懂你遇到的麻烦了——你直接调用My.Resources.Logo_Reports时,拿到的其实是一个Bitmap对象,而不是文件路径或者字节流,这就是File.Copy和直接用File.WriteAllBytes报错的根源!下面给你两种靠谱的解决方案,覆盖PNG、TXT等各类资源文件:
方法1:将Bitmap对象转为字节数组写入文件
如果你的图片资源是作为Bitmap类型添加的,可以通过MemoryStream把它转换成字节数组,再写入本地文件:
Dim targetPath As String = System.IO.Path.Combine(FileFolderOther, "LogoReport.png") ' 先确保目标文件夹存在,避免路径不存在的错误 If Not System.IO.Directory.Exists(FileFolderOther) Then System.IO.Directory.CreateDirectory(FileFolderOther) End If If Not System.IO.File.Exists(targetPath) Then ' 使用Using语句自动释放资源,避免内存泄漏 Using ms As New System.IO.MemoryStream() ' 将Bitmap保存到内存流 My.Resources.Logo_Reports.Save(ms, System.Drawing.Imaging.ImageFormat.Png) ' 将流转为字节数组并写入文件 System.IO.File.WriteAllBytes(targetPath, ms.ToArray()) End Using End If
方法2:直接读取嵌入资源流(更通用,支持所有文件类型)
如果你的资源(不管是PNG还是TXT)是作为嵌入的资源添加的(可以在资源属性里把「生成操作」改成「嵌入的资源」),这种方法更直接,不需要处理类型转换:
Dim targetPath As String = System.IO.Path.Combine(FileFolderOther, "LogoReport.png") ' 资源名称格式:项目命名空间.资源文件夹.文件名(如果资源在文件夹里的话) Dim resourceName As String = "YourProjectNamespace.Resources.Logo_Reports.png" If Not System.IO.Directory.Exists(FileFolderOther) Then System.IO.Directory.CreateDirectory(FileFolderOther) End If If Not System.IO.File.Exists(targetPath) Then ' 获取当前程序集的嵌入资源流 Using stream As System.IO.Stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName) If stream IsNot Nothing Then ' 将流写入本地文件 Using fileStream As New System.IO.FileStream(targetPath, System.IO.FileMode.Create) stream.CopyTo(fileStream) End Using End If End Using End If
额外提醒
- 替换代码里的
YourProjectNamespace为你实际的项目命名空间(可以在项目属性里查看) - 确保资源的「生成操作」设置正确:如果想按Bitmap类型调用就选「Resource」,如果想通用读取所有文件类型就选「嵌入的资源」
- 一定要先检查目标文件夹是否存在,避免因路径不存在导致的写入失败
内容的提问来源于stack exchange,提问作者Thomas Dutoit
相关产品推荐
相关产品推荐

