Solved

I want to find Content Type based on File Extention. Is there any in build function in C# or can anyone guide me how to do that?

Posted on 2010-08-13
8
497 Views
Last Modified: 2013-12-14
I want to find Content Type based on File Extention. Is there any in build function in C# or can anyone guide me how to do that?
0
Comment
Question by:divteam
8 Comments
 
LVL 5

Expert Comment

by:almander
Comment Utility
You can look in the registry in HKEY_CLASSES_ROOT  for the extension and read the REG_SZ value that identifies the content type.
0
 
LVL 11

Expert Comment

by:ladarling
Comment Utility
Here are some classes that return the file association in the OS :
http://www.codeproject.com/KB/dotnet/System_File_Association.aspx
If you are referring to content type as binary or string then you could test with readers in the IO namespace.
 
0
 
LVL 5

Expert Comment

by:chinawal
Comment Utility
When you say 'Content Type', is that type of file e.g. Word Document vs Web pages vs XML documents etc.?
Extension and those types are stored in Windows Registry.  Try search some windows API  
0
 
LVL 18

Expert Comment

by:Anil Golamari
Comment Utility
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 16

Expert Comment

by:kris_per
Comment Utility

Content type - file extension mapping is available in the registry in

\\HKEY_CLASSES_ROOT\MIME\Database\Content Type

For example

HKEY_CLASSES_ROOT\MIME\Database\Content Type\application/pdf

has Extension value = .pdf.

You can write a c# method to get this type from file extension.
0
 
LVL 16

Expert Comment

by:Vikram Singh Saini
Comment Utility
Hi,

Check code. I am trying to find .xml files. Modify it as your requirements.
Regards,
V.S.Saini

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace ee_XmlFileArray
{
    public partial class Form1 : Form
    {
        ArrayList arrFiles = new ArrayList();
        public Form1()
        {
            InitializeComponent();
        }

        private void btnGet_Click(object sender, EventArgs e)
        {            
            DirectoryInfo dir = new DirectoryInfo(@"D:\Zodes");

            foreach (FileInfo file in dir.GetFiles())
            {
                if (file.Extension.Equals(".xml"))
                {
                    arrFiles.Add(file.Name);            
                }               
            }

            if (arrFiles.Count > 0)
            {
                for (int i = 0; i < arrFiles.Count; i++)
                {
                    rtbFiles.Text += arrFiles[i].ToString() + "|";
                }
            }
        }        
    }
}

Open in new window

0
 

Author Comment

by:divteam
Comment Utility
I am trying to upload file from outlook email into database and I need to find ContentType. I do have file extention but it does not seem to be working fine. Even though it upload successfully, when i try to view the attachment, it always error out with message saying "invalid format".

Any idea how to upload email attachments into Database?

Note:- I am using SQL 2000 and storing as image.

byte[] data = new byte[item.Attachments[a].Size];
                                int bytes_read = 0;

                                sql = @"insert into bug_post_attachments
                                          (bpa_post, bpa_content)
                                          values (@bp, @bc)";
                                using (SqlCommand cmd = new SqlCommand(sql))
                                {
                                    cmd.Parameters.AddWithValue("@bp", bp_id);
                                    cmd.Parameters.Add("@bc", SqlDbType.Image).Value = data;
                                    DbUtil.execute_nonquery(cmd);
                                }
upload-error.bmp
0
 
LVL 16

Accepted Solution

by:
kris_per earned 500 total points
Comment Utility

I am not sure why do you want to find the content type or where you use it...

For the xlsx file to open, hope ms office 2007 or higher is installed in that machine.

If ms office 2007 is already installed, then it may be what the data bytes array contains...can you post the code that loads the attachment into data bytes array...

Below is a similar code that saves the file into database which is working fine...this can be compared with your code...
private void cmdSave_Click(object sender, EventArgs e)

{

    try

    {

          //Read Image Bytes into a byte array

          byte[] imageData = ReadFile(txtImagePath.Text);

                

          //Initialize SQL Server Connection

          SqlConnection CN = new SqlConnection(txtConnectionString.Text);



          //Set insert query

          // ImageData column is sql image type

          string qry = "insert into ImagesStore 

		(OriginalPath,ImageData) values(@OriginalPath, @ImageData)";



          //Initialize SqlCommand object for insert.

          SqlCommand SqlCom = new SqlCommand(qry, CN);



          //We are passing Original Image Path and 

          //Image byte data as SQL parameters.

          SqlCom.Parameters.Add(new SqlParameter("@OriginalPath", 

			(object)txtImagePath.Text));

          SqlCom.Parameters.Add(new SqlParameter("@ImageData", (object)imageData)); // ImageData column is sql image type





          //Open connection and execute insert query.

          CN.Open();

          SqlCom.ExecuteNonQuery();

          CN.Close();



          //Close form and return to list or images.

          this.Close();

      }





byte[] ReadFile(string sPath)

{

    //Initialize byte array with a null value initially.

    byte[] data = null;



    //Use FileInfo object to get file size.

    FileInfo fInfo = new FileInfo(sPath);

    long numBytes = fInfo.Length;



    //Open FileStream to read file

    FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);



    //Use BinaryReader to read file stream into byte array.

    BinaryReader br = new BinaryReader(fStream);



    //When you use BinaryReader, you need to supply number of bytes 

    //to read from file.

    //In this case we want to read entire file. 

    //So supplying total number of bytes.

    data = br.ReadBytes((int)numBytes); 



    return data;

}

Open in new window

0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
The viewer will learn how to use and create keystrokes in Netbeans IDE 8.0 for Windows.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now