Identify a file type and open the file

  • Thread starter Thread starter Shilpa
  • Start date Start date
S

Shilpa

Hi All,

I want to write C# code to identify a file type and open the file in
the associated editor.
For example, text files should be identified and opened in notepad,
html should be opened in internet explorer/netscape/mozilla.
At design time, I do not know if internet explorer/netscape is
installed on the client machine. The C# code should identify that and
open.


Please help.


Regards,
Shilpa
 
Hi Shilpa,

There are a few ways to do this. I will describe three of them :

1. Files usually open in the associated editor by themself. So, you can
use :
System.Diagnostics.Process.Start("myProgram", "arguments");

Here myProgram is the path to the executable that opens the file, such
as Notepad.
Arguments is the FileName.

2. To generalize the above process, you can simply use :
System.Diagnostics.Process.Start("fileName");

This will automatically open any file in the associated program. If an
HTML file is selected, and multiple browsers are installed, it will
open the file in the System Default browser, be it IE, or Mozilla or
Netscape.

3. To account for cases where unrecognized file types may be passed as
parameters, you could a Select Case structure (Switch structure in C#),
wherein you could check the File Extenstion of each passed file and
make decisions accordingly :

FileInfo fi = new FileInfo("myFileName");
string ext = fi.Extension;
string fn = fi.FullName;

switch (ext)
{
case ".txt"
System.Diagnostics.Process.Start("notepad.exe", fn);
case ".pdf"
System.Diagnostics.Process.Start("AcroRd32.exe", fn);
:
:
:
}

Typed here, so watch for syntax...

Hope this helps,

Regards,

Cerebrus.
 
Back
Top