EdgeSharp icon indicating copy to clipboard operation
EdgeSharp copied to clipboard

Is it possible to access embedded resources of the assembly itself instead of local folders?

Open VAllens opened this issue 3 years ago • 3 comments

Is it possible to access embedded resources of the assembly itself instead of local folders? I just want to package it into a single-file application

VAllens avatar Sep 02 '22 08:09 VAllens

@VAllens apologies for the late response.

If you mean WebView2 core assemblies? At the beginning they were. I am not sure now that is it GA. But you can try. If you mean something else. Please explain.

Thanks.

mattkol avatar Sep 17 '22 19:09 mattkol

@mattkol I searched google for the keyword SetVirtualHostNameToFolderMapping and found this place.

I have some static resource files (html, js, css, etc...). If I decide not to embed them in an assembly resource, then I can use the SetVirtualHostNameToFolderMapping method to map them to a local folder so they are ready to use out of the box. If I decide to embed them in an assembly resource, then I need to do extra work to handle some events, parse the request, and fetch the target resource from the assembly resource and finally respond.

I decide to embed them in an assembly resource, i solved it.

VAllens avatar Sep 18 '22 03:09 VAllens

I don't want these static resource files to be exposed to users or visible in any directory on the computer. And to prevent users from tampering with these static resource files, I embed them in the assembly resources.

VAllens avatar Sep 18 '22 03:09 VAllens

I decide to embed them in an assembly resource, i solved it.

Cool! If this something you think will be useful for others, you can share a bare skeletal version. Thanks.

mattkol avatar Sep 22 '22 10:09 mattkol

Of course. Let's embrace open source !!!

I will take the time to organize the code and then share it. Here are a few methods and events to keep an eye on:

  • CoreWebView2InitializationCompleted
  • CoreWebView2.WebResourceRequested
  • CoreWebView2.AddWebResourceRequestedFilter($"file://your_custom_alias/*", CoreWebView2WebResourceContext.All)
  • CoreWebView2.Environment.CreateWebResourceResponse(...)
  • Assembly.GetExecutingAssembly().GetManifestResourceStream(...)

We register the CoreWebView2InitializationCompleted event. Then in the CoreWebView2InitializationCompleted callback method, we register the internal events of CoreWebView2.WebResourceRequested and call CoreWebView2.AddWebResourceRequestedFilter method.

We process the file:// request in the CoreWebView2.WebResourceRequested callback method, fetch the assembly resource file by relative URL, and respond stream.

Be careful. Be sure to use file:// instead of http://. Issues: 2 seconds delay is seen with Page navigation using WebView2 & SetVirtualHostNameToFolderMapping

VAllens avatar Sep 23 '22 02:09 VAllens