Pages

Wednesday 16 May 2012

Accessing local HTML files inside Silverlight OOB application

Hi Guys,
    I have been actively participating in Silverlight.net,  so i couldn't post here in the last 2 weeks.  Well the forums are amazing, you get to learn a whole lot of things there.   But first, let me tell you scenario .

A guy developed a  Html 5 application,  but he also wanted a standalone desktop application also. 
He didnt want to recode everything, so he wanted to make an OOB application that shows the HTML.
This is really a big advantage if you dont want to have internet connectivity , but still want to access that app.
After a bit of work, i finally came up with a solution that worked.    

1)  I added the Html page to my project  and changed its Build Action to "Embedded Resource".
2) Next, i tried to access that resource file path through code.
3) This is an out of browser application, so that i could use the Web Browser control.
4) I used Streams to read the data from the html resource and display it in the browser control.

It looks pretty straightforward, right :)   Here the code for the thing...

            Assembly thisAssembly = Assembly.GetExecutingAssembly();  
            string[] resNames = thisAssembly.GetManifestResourceNames(); 
            foreach (string resName in resNames)
            {
                if (resName.ToLower().EndsWith("hello.html"))  
                {
                    // To get only the file name
                    int j = resName.IndexOf('.');
                    string myres = resName.Substring(j+1);
                    
                    
                    // To get the folder where that file is present.
                    string str = Application.Current.Host.Source.LocalPath.ToString();
                    int i = str.LastIndexOf('\\');
                    str = str.Substring(0, i+1);
                    str += myres;

                    //Open the html in the browser
                    FileStream fs = new FileStream(str, FileMode.Open, FileAccess.Read);
                    StreamReader sr = new StreamReader(fs);
                    string s = sr.ReadToEnd();
                    sr.Close();
                    fs.Close();
                    webBrowser1.NavigateToString(s);
                    break;

                }
            } 
 
And so, all of you who want ot create desktop versions of Html pages can happily do so :)   

P.S :   I love the forums because you are faced with fascinating scenarios and challenges.  You could never have encountered all of them on your own . You also brush up with the basics , and more importantly , you get to know what to use in specific scenarios.

P.P.S :  I havent forgotten my agenda. I am currently working on the Silverlight Social Networking site.  Will start posting the content soon :) 

No comments:

Post a Comment