Blue Theme Orange Theme Green Theme Red Theme
 
MindFusion's Components
Home | Forums | Videos | Photos | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Visual Studio 2010 » Create your own Custom File Type

Create your own Custom File Type

This article describes a simple approach to creating a custom file type.

Author Rank:
Technologies: .NET 1.0/1.1, Windows Forms,Visual C# .NET
Total downloads : 737
Total page views :  29366
Rating :
 3.5/5
This article has been rated :  2 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
CustomFileType.zip
 
ArticleAd
Become a Sponsor



Introduction:

This article describes a simple approach to creating a custom file type.  In the example provided, a custom file type is created around a serializable class that is used as a data container holding all of the elements necessary to support an application designed to interact with the defined file type.  A separate module is used to serialize and deserialize files of this user defined file type.

It is possible to include more than a single data container class as the basis for the file type; placing a collection of objects into a hash table will allow for greater complexity but will still operate in the same manner.  The approach is useful if you are in need of a way to create a file type that is specific to a particular application.

Getting Started:

In order to get started, unzip the downloaded files and open the project provided.  Within the project you will find three main files: frmMain.cs, ProjectSerializer.cs, and PersonalData.cs.

frmMain.cs:  This is the application and it is used to represent an application that interacts exclusively with the custom file type.  This form contains a collection of text boxes used to capture or display values associated with instances of the PersonalData class.  It only contains three primary functions, one to save a file as the custom type, one to open a file on startup, and one to open a file of the custom type through a file open dialog.  To open a file, the application captures the path to the file by means of an OpenFileDialog, the path of the file along with a new instance of the PersonalData class is subsequently passed to the ProjectSerializer's deserialize function which in turn deserializes the content of the stored file and passes it back to the Open File function.  Once the deserialized values are applied back to the PersonalData object, the Open File function populates the form textboxes from the values contained in that object.  To save a file, the values currently displayed in the form's text boxes are gathered and used to populate the properties contained in a new instance of the PersonalData class.  The class along with the file path captured from a SaveFileDialog are passed to the ProjectSerializer's serialize method where a binary formatter is used to serialize the object's content into a file created at the specified file path.

ProjectSerializer.cs:  This is a module that contains two functions; one to serialize the data contained on the form and one to deserialize the data from a stored file saved as the custom file type.  Both methods use the binary formatter although it would work equally well with soap formatter.

PersonalData.cs:  A serializable class used contain the data associated with an instance of a custom file type as generated from the fields on in the frmMain form.  One important point to make here is that this class is defined as serializable; if it were not the operation would fail.

Each of the files mentioned herein are contained in the sample application; the code is fairly well annotated and should be straight forward and easy to follow.  Sufficient annotation is contained within these files so they should be easy enough to understand.  At this point, you may wish to open the project, run it to see how it works, and then examine the code files to see how the project was constructed.

Creating a File Type Association.

The process of creating a file type association through the use of the Visual Studio 2005 setup and deployment project is far easier to manage than it once was; you can manually code the necessary information into the application, and depending upon the installation package you are using, you may need to do that.  If you are interested in that approach, take a look at this link,

http://www.vbcity.com/forums/faq.asp?fid=15&cat=Registry#TID72502, [see File Associations the hard way].

First off, in the main form of the application, you will need to modify the form load event handler to respond to the receipt of a command line argument (the file name), this is now a trivial bit of code and it should look something like this:

Private void frmMain_Load(System.Object sender, System.EventArgs e)

{

    'check each parameter to get the file name (there is only one though)

    for (String In My.Application.CommandLineArgs param)

 {

        try

        {

            ' pass the file path if it exists

            OpenFromPath(param);

        }

        catch

       {

            'do nothing, just open the application with no file

        } 

   } 

}

In this example, when the form loads, it will examine the contents of My.Application.CommandLineArgs to see if it contains a file name; since that is all we are going pass in, it will either be empty or will contain a file path.   If a file path is present, it will passed to a subroutine called, "OpenFromPath" which captures the data from the file and populates the form's text boxes.

In order to pass the file path to the command line arguments, you need to set up a couple of things in the Setup and Deployment project.  To begin, add a setup and deployment project to the existing solution and configure it to suit your requirements (the sample code include a setup project).  Once the project has been added, click on the setup project's name in the solution explorer, click on the "View" and then click on the "File Types" option.  This will bring up a File Types Designer in the main window of Visual Studio.

Once the file type designer has been displayed, right click on "File Types on Target Machine" and the click on the "Add File Type" option.  This will add an empty file type to the tree view, select the new file type's node and look in the property editor:

Figure 1:  File Type Property Editor

In the property editor, set the name to match the name of the custom type, set the command to point to the application (as the Primary output from the application), key in a description, set the extension to the custom file type's extension, and set an icon for the file type.  Having set those values, click on the Open node.


 
Figure 2:  The Open node under the custom file type

Once you have clicked on the open node, the property editor will show these properties:


 
Figure 3:  Property Editor Set to the Open Node

These default properties are correct in that the default process is set to "open" and the "%1" is set to pass the file name of a selected file to the application's command line arguments on startup.  After a user installs the application, when they double click on a file of the custom file type, it will pass the file path to the application and open it.  Also, if the user right clicks on the custom file type icon, they will be able to select the "open with" option and be presented with a link to your application as indicated in the following figure:


 
Figure 4: Open With option in Windows Explorer context menu

NOTE: THIS ARTICLE IS CONVERTED FROM VB.NET TO C# USING A CONVERSION TOOL. ORIGINAL ARTICLE CAN BE FOUND ON VB.NET Heaven (http://www.vbdotnetheaven.com/).


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Scott Lysle
Freelance software developer residing in Alabama. Bachelors, Masters Degrees from Wichita State University. I spent the first half of my career working on aircraft controls and displays and in that time I worked on the cockpits for the OH-58 AHIP, the AH-1W, the V-22, the F-22, the C-130J, the C-5 AMP, AWACS, JPATS, and a few others. Since 1997 I have been largely involved with Windows and web development, GIS application development, consumer electronics development (embedded linux/java), but still sometimes work on aircraft and military projects, the most recent of which was the presidential transport helicopter. I tend to work primarily with C/C++, Java, VB, and C#.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Boost the performance of your .NET applications
“ANTS Profiler took us straight to the specific areas of our code which were the cause of our performance issues." Terry Phillips, Sr. Developer, Harley-Davidson Dealer Systems. Download your free trial of ANTS Profiler.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
CustomFileType.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
ArticleAd
Become a Sponsor
Latest Comments:
Subject Posted By Posted On
Setup applicationJacob1/9/2007
thiere is no project type for setup or distribution on visual c# program. do you download a new project type.
Reply | Email | Delete | Modify | 
 
 
Re: Setup applicationScott1/10/2007
No you don't need to download anything, in the create project dialog there is an option for "Other Project Types", under that section is the "Setup and Deployment" option.
Reply | Email | Delete | Modify | 
 
Re: Re: Setup applicationRobert1/29/2007
There is no Other Project Types? I think i may have the newest version where they have taken it out or something. :@
Reply | Email | Delete | Modify | 
 
Re: Re: Re: Setup applicationScott1/29/2007
Well, I run Team Studio and Professional in 2005, and Enterprise Architect in 2003 and it is there in all of them; what version of Visual Studio are you running?  Are you running an Express version?
Reply | Email | Delete | Modify | 
unrecongnised slash sequence error amrishwa2/2/2008
what to do
Reply | Email | Delete | Modify | 
 
 
Re: unrecongnised slash sequence error Scott2/3/2008

Can you provide more information; for example, a stacktrace.  I did not encounter any such errors.  In the section of code generating the error, you might check for an illegal escape sequence (such as a file path name) to see if that is the problem; if it is that, use a literal or double slashes. 

Thanks, Scott

Reply | Email | Delete | Modify | 
Problem saving file *.prd in another fileLuis4/27/2009
Hi!, This post is very cool and I've learned a lot with it. But now I have a doubt... Imagine that you need some information that is in an app.config file. If you save the .prd file in the bin.debug, everything thing works really fine But if you save the .prd file in the desktop, e.g., the system can´t find the app.config file. It's like having a MS Word that only allows you to save the .doc files in a predifined directory. Is this a problem that you also got? Thank a lot, Luis
Reply | Email | Delete | Modify | 
 
 
Re: Problem saving file *.prd in another fileLuis4/27/2009
Forget about my question.

I was having troubles because in my project I had  references to the used DLL's assuming that I was allways in bin/debug folder.
And when I've tried to save my custom type file in another folder i was searching for the DLL references in that folder, not in bin/debug file!

It's done! ;)
Reply | Email | Delete | Modify | 
 
Re: Re: Problem saving file *.prd in another fileScott4/27/2009
Ok.  You can actually save and open the file from any location; that does not matter (and you can name it anything you want to use for a file extension by altering the code).
Reply | Email | Delete | Modify | 
Error in modregistry.cs fileKapil5/18/2009

using System;

using Microsoft.Win32;

namespace CustomFileType

{

/// <summary>

/// Summary description for modRegistry.

/// </summary>

public class modRegistry

{

//Credit: http://www.devx.com/vb2themax/Tip/19554, author Marco Bellinaso

//

// Nifty little function to create the file association.

// Displays the default application icon inside an icon that looks like a page

// outline instead of using a specified icon. Made a couple of minor changes

//to remove warnings in the original version but essentially it is the

// the same as the original code. This is a nice approach because the

// association occurs immediately.

public modRegistry()

{

//

// TODO: Add constructor logic here

//

}

}

[System.Runtime.InteropServices.DllImport("shell32.dll")]

public void SHChangeNotify(int wEventId ,int uFlags,int dwItem1 ,int dwItem2 )

{

}

// Create the new file association

//

// Extension is the extension to be registered (eg ".prd")

// ClassName is the name of the associated class (eg "PersonalDocumentRecord")

// Description is the textual description (eg "Personal Record Document")

// ExeProgram is the app that manages that extension (eg Application.StartupPath & "CustomFileType.exe")

function CreateFileAssociation(string extension,string className,string description ,string exeProgram)

Const SHCNE_ASSOCCHANGED = &H8000000

Const SHCNF_IDLIST = 0

// ensure that there is a leading period in the extension (e.g. ".prd")

if extension.Substring(0, 1) <> "."

extension = "." & extension

Microsoft.Win32.RegistryKey Key1 = Nothing;

Microsoft.Win32.RegistryKey Key2 = Nothing;

Microsoft.Win32.RegistryKey Key3 = Nothing;

try

{

// create a value for this key that contains the classname

key1 = Microsoft.Win32.Registry.ClassesRoot.CreateSubKey(extension);

key1.SetValue("", className);

//create a new key for the Class name

key2 = Microsoft.Win32.Registry.ClassesRoot.CreateSubKey(className);

key2.SetValue("", description);

// associate the program to open the files with this extension

key3 = Microsoft.Win32.Registry.ClassesRoot.CreateSubKey(className & _

"\\Shell\\Open\\Command");

key3.SetValue("", exeProgram & " ""%1""");

}

Catch(Exception e)

{

return False

}

finally

if Not key1 Is Nothing key1.Close();

if Not key2 Is Nothing key2.Close();

if Not key3 Is Nothing key3.Close();

// notify Windows that file associations have changed

SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, 0, 0)

return True

}


in the above code in SHChangeNotify, i m getting "Expected class, delegate, enum, interface, or struct" error.

Reply | Email | Delete | Modify | 
 
 
Re: Error in modregistry.cs fileScott5/19/2009
Check your paranthesis beginnings and endings and make sure that everything is defined within the class.
Reply | Email | Delete | Modify | 
 
Re: Re: Error in modregistry.cs fileJoberto6/16/2009
Nessa classe "modRegistry" tem um monte de erro..código escrito em VB...
alguém tem o código correto dela?
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved