To save traffic, we may need to cache images locally in the program. During the second display, we can directly read images from the local machine without downloading them from the network.
In particular, apps such as news sometimes use WebBrowser to display news content. How can we make WebBrowser use cached images? There are two methods:
1. Use the absolute path of the image to directly reference it.
2. Use the relative path of the image to Create html file display
This article describes the two methods in the form of a simple demo:
First, copy an image in the project to an independent bucket.
Private void SaveFilesToIsoStore () {// These files must match what is stored in the application package, // or BinaryStream. dispose below will throw an exception. string [] files = {"1.jpg"}; IsolatedStorageFile isoStore = IsolatedStorageFile. getUserStoreForApplication (); if (false = isoStore. fileExists (files [0]) {foreach (string f in files) {StreamResourceInfo sr = Application. getResourceStream (new Uri (f, UriKind. relative); using (BinaryReader br = new BinaryReader (sr. stream) {byte [] data = br. readBytes (int) sr. stream. length); SaveToIsoStore (f, data) ;}}} private void SaveToIsoStore (string fileName, byte [] data) {string strBaseDir = string. empty; string delimStr = "/"; char [] delimiter = delimStr. toCharArray (); string [] dirsPath = fileName. split (delimiter); // Get the IsoStore. isolatedStorageFile isoStore = IsolatedStorageFile. getUserStoreForApplication (); // Re-create the directory structure. for (int I = 0; I <dirsPath. length-1; I ++) {strBaseDir = System. IO. path. combine (strBaseDir, dirsPath [I]); isoStore. createDirectory (strBaseDir);} // Remove the existing file. if (isoStore. fileExists (fileName) {isoStore. deleteFile (fileName);} // Write the file. using (BinaryWriter bw = new BinaryWriter (isoStore. createFile (fileName) {bw. write (data); bw. close () ;}} Method 1: use absolute path
private void DisplayUsingAbsolutePath(){ string appPath = string.Format("file:///Applications/Data/{0}/Data/IsolatedStore", "ac85cd27-463a-4258-9fd2-a45dba5beb0a"); string imgPath = appPath + "/1.jpg"; webBrowser1.NavigateToString("
{0} is the app id of the application. We piece together html. The src path used by the img tag is the absolute path of the image.
Method 2: Use relative path
private void AnotherWayToReferImageInIso(){ //create html string htmlPath = "index.htm"; string html = "
Create an html file. The path of the image referenced by html is the path of the image relative to the html file, and then display the html file.
The source code can be obtained here.