How To Open Documents With External Applications


This step-by-step tutorial demonstrates how to add an Open With button that opens a document in an external application. The proposed solution uses COM automation and therefore only works for applications that runs with elevated permissions.

This tutorial extends the How To Download and Update Documents tutorial. Complete that tutorial first before starting.

1) Open the LightSwitch project created in the How To Download and Update Documents tutorial in Visual Studio 2010.

2) Open the DocumentDetails screen in the designer, add a new button to the Document Viewer command and name the method OpenWith.

OpenWith.png

3) Edit the Execute code of the button and add the following code:

C#
using System.Runtime.InteropServices.Automation;

partial void OpenWith_Execute()
{
  if (!System.Windows.Application.Current.HasElevatedPermissions) {
    throw new NotSupportedException("Must run with elevated permissions");
  }

  // write document to temp file with unique name
  var tempFile = GetTempFileName(this.Document.Name);
  File.WriteAllBytes(tempFile, this.Document.File);

  // open the temp file using Shell Object
  var shell = AutomationFactory.CreateObject("WScript.Shell");
  shell.Run(string.Format("\"{0}\"", tempFile)); // must enclose in quotes
}

VB.NET
Imports System.Runtime.InteropServices.Automation

Private Sub OpenWith_Execute()
  If Not System.Windows.Application.Current.HasElevatedPermissions Then
    Throw New NotSupportedException("Must run with elevated permissions")
  End If

  ' write document to temp file with unique name
  Dim tempFile = GetTempFileName(Me.Document.Name)
  File.WriteAllBytes(tempFile, Me.Document.File)

  ' open the temp file using Shell Object
  Dim shell = AutomationFactory.CreateObject("WScript.Shell")
  shell.Run(ChrW(34) + tempFile + ChrW(34)) ' must enclose in quotes
End Sub

The code checks whether the application is running with elevated permissions, if that is not the case an exception is raised. A temp file name is generated by invoking the GetTempFileName method (described below). The entire document binary is then written to the temp file.

The object WScript.Shell is created. This automation object is part of the Window Script Host that is pre-installed on all Windows machines. The shell object contains a Run method that is used to launch the created temp file.

4) Add the GetTempFileName method as defined below:

C#
private string GetTempFileName(string fileName)
{
  // create temp folder in My Documents
  var tempFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyTempDocuments");
  if (!Directory.Exists(tempFolder)) {
    Directory.CreateDirectory(tempFolder);
  }
  // generate unique file name while retaining file extension
  return Path.Combine(tempFolder, string.Format("{0}.{1}", Guid.NewGuid(), fileName));
}

VB.NET
Private Function GetTempFileName(ByVal fileName As String)
  ' create temp folder in My Documents
  Dim tempFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyTempDocuments")
  If Not Directory.Exists(tempFolder) Then
    Directory.CreateDirectory(tempFolder)
  End If

  ' generate unique file name while retaining file extension
  GetTempFileName = Path.Combine(tempFolder, String.Format("{0}.{1}", Guid.NewGuid(), fileName))
End Function

The created temp file has the same file extension as the original document file name. This is mandatory because the file extension is used to determine which application to launch. File extension .docx for instance will launch Microsoft Word (if installed).

The temp folder is created in the My Documents folder of the current user. Silverlight Out-Of-Browser applications only have access to a limited set of user folder on disk, you cannot access the Windows temp folder.

Important: The temp folder is not cleared, it is left as an exercise to the reader to implement a mechanism to clear the temp folder where appropiate.


5) Compile and run the application. Select a document and click the Open With button will open the document in an external application.

ExternalApp.png


Next step: learn more about the Document Toolkit Client API in How To Take Advantage Of The Document Toolkit Client API.

Last edited Jul 12, 2011 at 11:58 AM by kozw, version 4

Comments

No comments yet.