How to get a Full File Path in Silverlight

Usually a Silverlight application it's not allowed to access a FileInfo's full path attribute, even via reflection. This because of security policy.

But sometimes, for our applications, we need to store a file's path, especially if talking about network directories. To workaround this we can use Javascript! Honesty I hate Javascript, but some times there is no other way. Silverlight is even too much secure for production applications!

The idea is to grant access to path by using javascript and then send back the property to Silverlight for our use. Here you can find the sample project


Please refer to this article and this article if you don't know how Silverlight/Javascript communication works.

NOTE: This solution will perfectly work on IE, will only show file name on Firefox and won't work on Chrome, because of Input element implementation... :@ 




First let's add this script code to our .aspx/.html page's head
<script type="text/javascript">
   var silverlightCtrl = null//the Silverlight object

   function pluginLoaded(sender, args) {
       silverlightCtrl = sender.getHost();
   }

   function JS_GetFilePath() {
       document.getElementById("my_file_element").click();
   }

   function sendPathToSL() {
       var element = document.getElementById("my_file_element");
       silverlightCtrl.Content.SL2JS.SL_SetFilePath(element.value);
   }
</script>




Then this to the Silverlight's object element
<param name="onLoad" value="pluginLoaded" />



And finally this at the end of the body element.
<form enctype="multipart/form-data" method="post" style="visibility:hidden; height:0px; width:0px; border:0px; overflow:hidden">
        <input id="my_file_element" type="file" name="file_1" onchange="sendPathToSL();">
 </form>



Now we can move to Silverlight project. What you need to add it's just 3 parts in your class:

  • The registration to scriptable object in the constructor: HtmlPage.RegisterScriptableObject("SL2JS"this);
  • The invoke event in the click (command) of some button that will ask Javascript to do job: System.Windows.Browser.HtmlPage.Window.Invoke("JS_GetFilePath");
  • And the scriptable member that will get Javascript's answer:
    [ScriptableMember]
    public void SL_SetFilePath(string path)
    {
        Txt_Path.Text = path;
    }


The (partial) class should look like:

public partial class MainPage : UserControl
{
   public MainPage()
   {
       InitializeComponent();
       HtmlPage.RegisterScriptableObject("SL2JS"this);
   }

   private void Button1_Click(object sender, RoutedEventArgs e)
   {      
       System.Windows.Browser.HtmlPage.Window.Invoke("JS_GetFilePath");
   }

   [ScriptableMember]
   public void SL_SetFilePath(string path)
   {
       Txt_Path.Text = path;
   }
}


Hope it helps! ;-) See ya!

Commenti

Post più popolari