Silverlight 4 introduces some nice functionality on top of the Out Of Browser (OOB) capabilities introduced in Silverlight 3. The application can now be granted a higher level of trust which allows it to operate outside the Silverlight sandbox file system, and to interact with COM. To test the capabilities of this new functionality I immediately tried to take it file system access far beyond the sandbox; I wanted to enumerate all of the drives on the client machine. I quickly ran into a wall. Silverlight does not expose access to drives through its IO libraries. Why? I read several answers to this question, none of which satisfied me, especially given the fact that the app can simply access these drives through COM!
Luckily .Net 4.0 / Silverlight 4.0 / C# 4.0 comes with the Dynamic Language Runtime (DLR). I had previous used the new dynamic pseudo-type that ties into the DLR to call Iron Python. I figured I would see if I could use this same technique to call into COM. Back in ancient times (circa 1990s) I called into COM all the time from VB and ASP. I knew the libraries were all there to do what I needed to do.
I was not surprised to find I wasn’t the first person down this path, and quickly encountered multiple articles and postings about working with the file system via COM this exact way. With the knowledge that it was possible I plowed forward.
To access COM from Silverlight one uses the AutomationFactory to instantiate a COM library. I wanted to use the good ol’ Scripting.FileSystemObject. In my test case I had a Silverlight app running locally OOB with elevated privileges. This Silverlight app has a single list box which will display the drive letters once I can get access. Via COM, the code looks like this:
dynamic fs = AutomationFactory.CreateObject("Scripting.FileSystemObject");
foreach (dynamic drive in fs.Drives)
{
filesListBox.Items.Add(drive.DriveLetter);
}
Its really that simple. The dynamic keyword and COM do all the heavy lifting. The most work I had to do was lookup the object model to use in the FSO, as no intellisense is available. The runtime does late binding onto these properties via the DLR. This did a nice end-route around the missing Silverlight IO libraries and provided me with a nice list of drives.
