Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I assign a relative path of an embed image to a ActiveSheet.PageSetup.LeftHeaderPicture.FileName?

Tags:

c#

There are 2 SSCCEs for this:

1.

I have added a picture to my VSTO document-level add-in by right clicking the solution -> add -> existing item -> myPic.jpg.

Now I am working with an Excel spreadsheet and want to add a picture to the top left header. Using PageSetup.LeftHeaderPicture.FileName and providing an absolute path to the picture it loads just fine while debugging.

When I am trying to change the path to not-absolute and say something like

ActiveSheet.PageSetup.LeftHeaderPicture.FileName = "\\Assets\\myPic.jpg"

I keep getting a HRESULT: 0x800A03EC exception.

enter image description here

I think I am not getting the correct syntax for to access the Assets\myPic.jpg.

2.

I have added a new resource, selected an existing item and selected the myPic.jpg. I can access it via Resource1.myPic but ActiveSheet.PageSetup.LeftHeaderPicture is read-only...

The PageSetup.LeftHeaderPicture.FileName needs a string type parameter and I am not sure how to retrieve the path to my already embed resource...

Q:

How do I embed a picture in my solution as a resource (or just an existing item) to be able to use it with PageSetup.LeftHeaderPicture.FileName?


1 Answers

Right, I have solved it.

Added an existing item myPic.jpg to the solution and set Build Action to Content and Copy to Output Directory to Copy Always (but I am sure you can set it to copy if newer)

enter image description here

Note: With this setup your file always gets "copied" to the published directory.

enter image description here

Now all you need in your code is

ws.PageSetup.LeftHeaderPicture.Filename = 
                           AppDomain.CurrentDomain.BaseDirectory + "\\myPic.jpg";
ws.PageSetup.LeftHeader = "&G";

AppDomain.CurrentDomain.BaseDirectory is very well explained here

and the end result as expected

enter image description here