Tech Talk A software developer on all things tech, and then some

5May/115

Open Documents and Media in WPF’s Web Browser Control in C#

Ever need to display a word document in the same application and didn't want to shell execute word? Ever need to display text from a rich text file or regular text file? How about quickly displaying an image file? All of these could use there own controls in WPF (Document Viewer, Image control, etc..), however if you use the web browser control, you can display all of these dynamically.  There might be a better solution for one, or all of these. I just thought I would include a quick tutorial on how to do it for those who need it done quickly and it works. This was done in WPF, using C# and the 4.0 Framework.

Rich Text or Text Format

If you have a rich text format (rtf), text format (txt), or a file that uses plain text, an easy way to display it in the web browser is through a stream.

byte[] attachment = System.IO.File.ReadAllBytes(fileName);
MemoryStream mStream = new MemoryStream(attachment);
browser.NavigateToStream((Stream)mStream);

FileName - The name of the plain text file.
browser - A web browser control.

Image File

The quick and easy way for me to display an image is to just set the source of the browser to the  absolute location of the image i.e. "C:\Images\bacon.png".

String uri = "C:\Images\bacon.png";
browser.Source = uri != null ? new Uri(uri) : null;

browser - A web browser control.

Microsoft Word Document, Spreadsheets, etc...

This was the tricky object to display. If you try to read in the file, you will just see it encrypted in a Binary format. If you try to set the source to the file, you will just end up downloading the file. To be able to view the document within the browser, you can open the file up into a document using the Microsoft.Office.Interop.Word Namespace, then save as an html file. Then load this into the browser control. I know this is a horrible work around, but it works!

string[] SplitHTML = fileName.Split('.');
string NameNoExt = SplitHTML[0];
string FileAsHtml = NameNoExt + ".html";

//Word with the document
Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document _doc = wordApp.Documents.Open(uri);
_doc.SaveAs2(FileAsHtml, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML);
_doc.Close(false);
wordApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(_doc);
browser.Navigate(FileAsHtml);

FileName - The name of the plain text file.
browser - A web browser control.

Feel free to leave comments and tell me how to make this better!

Comments (5) Trackbacks (0)
  1. hi this works fine
    but ppt and exel files are not sworking with this code

    also can you handle pdf files

    • Correct. You’ll have to change out the Microsoft.Office.Interop.Word with Excel, powerpoint, etc… to get the proper interop.

      As for the PDFs, WPF actually doesn’t handle that natively I believe. You’d be better off going with a third party control. If you would like to push to Adobe Acrobat Reader or something similar, you could use

      String fileName = “FileName.pdf”;
      System.Diagnostics.Process process = new System.Diagnostics.Process();
      process.StartInfo.FileName = fileName;
      process.Start();
      process.WaitForExit();

  2. This is one of the best answer so far, I have read online. Just useful information. Very well presented on WPF Web Browser control. Some other articles I was found too over internet during searching time of this article which also explained very well about WPF Web Browser control. Link URL of these posts are…..
    http://blogs.msdn.com/b/wpfsdk/archive/2008/08/18/wpf-webbrowser-control-sample.aspx
    http://www.c-sharpcorner.com/uploadfile/dhananjaycoder/web-browser-control-in-wpf/
    and
    http://mindstick.com/Articles/3610ee37-4b56-41fd-99b1-c4805b016901/?WebBrowser%20control%20in%20WPF

    Thanks Everyone for sharing your article with us.

  3. This has been a great help! I was having a lot of trouble getting it to work. I just have one problem. I am trying to view a .doc file that is being stored as a Byte[]. So if I utilize your code for displaying rtf or txt, I see the binary. But I can’t quite get it to work with the word document section because I do not have a uri. Is there another way to do this if the word/spreadsheet is saved as a byte[]?

    string fileName;
    byte[] fileArray;
    string fileExt;

    fileName = dg_attachments.GetCellValue(row, “attach_AnsweredText”).ToString();
    fileExt = Path.GetExtension(fileName);
    fileArray = (Byte[])dg_attachments.GetCellValue(row, “AttachmentVBM”);

    MemoryStream ms = new MemoryStream(fileArray);

    if (fileExt == “.txt”)
    {
    docBrowser.NavigateToStream((Stream)ms);
    }
    else if (fileExt == “.doc” || fileExt == “.docx”)
    {
    string[] SplitHTML = fileName.Split(‘.’);
    string NameNoExt = SplitHTML[0];
    string FileAsHtml = NameNoExt + “.html”;
    Uri myUri = new Uri((Uri)fileArray);

    Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
    Microsoft.Office.Interop.Word.Document _doc = wordApp.Documents.Open(uri);
    _doc.SaveAs2(FileAsHtml, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML);
    _doc.Close(false);
    wordApp.Quit();
    System.Runtime.InteropServices.Marshal.ReleaseComObject(_doc);
    docBrowser.Navigate(FileAsHtml);
    }

    That does not work because there is no uri (and (uri)fileArray does not convert!)

    • You could do something resembling the following if you didn’t have a lot of word documents to go through :

      //Word with the document
      Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
      var tmpFile = @”c:\TempDoc.doc”;
      var tmpFileStream = File.OpenWrite(tmpFile);
      tmpFileStream.Write(bytes, 0, bytes.Length);
      tmpFileStream.Close();

      This will create a temp file and write the byte array to it, allowing it to be opened by the Application.Open() method. There might be a better way to do this, but first thing that came to mind. Also, I’m not intimate with this project anymore, so I can’t guarantee 100% code accuracy, but should get you close enough. HTH!


Leave a Reply

No trackbacks yet.

%d bloggers like this: