this blog contains information for .net and sql stuffs. You can find various tips and tricks to overcome problem you may be facing in ...

Thursday, February 25, 2010

Open Different Application (word,excel,pdf etc.) From your .net Application

I think it’s very nice to launch, word document from your software and when require also launch jpg viewer software as you want to open Document from the internet and don’t wish to save it.

Firstly understand what you require then step by step we go through it.

Requirement: you are displaying different files to the user. If user wish to open any of the listed file, it should launch supported software and file should be readable there. If supported software is not installed in machine, it should give user friendly message.

Okay, now requirement is clear to our mind, first we need to know one thing that file can only be open if you have already opened, in internet first temporary files are created then you can watch it with your installed software.

In our application we need to decide where we store these temporary files. I think base directory is preferred place or you may store in the temporary file storage of your pc.

Below line first sets the Where to store files.

Dim fileName As String = AppDomain.CurrentDomain.BaseDirectory + "TempFiles\"

First create directory when you go to open file.

Directory.CreateDirectory(fileName)

Decide file name, it may be come from the data base or anything like it.

Dim flName As String = fileName + FileNamewithExtension.(i.e abc.doc, x.pdf)

Write data to created file

File.WriteAllBytes(flName, Me.dsFile.Attachment(0).Data)

Here dsFile is a dataset and has attachment table so we are writing bytes to file that we want to create. This data is stored in the image,or binary in the sql server. You can have directly byte array of file.

Now you have file on your machine, you just need to give path to that file and you can able to view it.

System.Diagnostics.Process.Start(flName)

At end, either the form closing or application close you need to delete all of the files created in the Temporary Directory.

If Directory.Exists(fileName) Then

Dim fi As String

For Each fi In Directory.GetFiles(fileName)

File.Delete(fi)

Next

Directory.Delete(fileName)

End If

We assumed that we are just storing files in the temporary directory,if you have directory that you need to delete it too.

If on the machine you don’t have application that can open the file, it will throw exception you can handle that window32 exception with giving a user friendly message.

Catch ex As System.ComponentModel.Win32Exception

MessageBox.Show("Required Software is not insalled on your machine.", "Can't Open", MessageBoxButtons.OK, MessageBoxIcon.Warning)

No comments: