Click here to Skip to main content
15,912,021 members
Please Sign up or sign in to vote.
2.60/5 (2 votes)
See more:
i hv a code use to open a file and Get the name and File Extesion aswell. On the basis of extension i need to change the connection string. Here is the code what i m doing..
C#
OpenFileDialog fd = new OpenFileDialog();
                fd.Title = "Select file to be upload";
                fd.Filter = "Excel Files (*.xls)|*.xls|Excel Files (*xlsx)|*.xlsx ";
               
                if (fd.ShowDialog() == DialogResult.OK)
                {
                    textBox1.Text = fd.FileName.ToString();
                   
                    string constr = "";
                     if(fd.)//code to compare extension
                    {
                         constr = @"Provider=Microsoft.Jet.OLEDB.12.0;Data Source= '" + textBox1.Text + "';Extended Properties='Excel 12.0;HDR=Yes;'";
                    }
                    else
                        if()
                        {
                             constr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= '" + textBox1.Text + "';Extended Properties='Excel 4.0;HDR=Yes;'";
                        }
Posted
Comments
ridoy 19-Jul-13 1:32am    
so what's the problem?!

To do this, you must handle the FileOK [^] event of your OpenFileDialog. Inside your event handler, you can use Path.GetExtension[^] to get the extension of the filename.
 
Share this answer
 
Use like this..
C#
if (fd.ShowDialog() == DialogResult.OK)
 {
     string str = fd.FileName;                    
     string strExt = System.IO.Path.GetExtension(str);


     if(strExt == ".txt")
     {
        //do your stuff
     }
     else if (strExt == ".rtf")
     {
        //do your stuff
     }
 
Share this answer
 
v3
C#
if(System.IO.Path.GetExtension(fd.FileName)==".xls")
}
}
else if(System.IO.Path.GetExtension(fd.FileName)==".doc")
{
}
.....
....
 
Share this answer
 
Use this:

C#
textBox1.Text = OpenFileDialog.SafeFileName;
string constr = Path.GetExtension(fd);
if(constr == ".xlsx")//code to compare extension
{
     constr = @"Provider=Microsoft.Jet.OLEDB.12.0;Data Source= '" + textBox1.Text + "';Extended Properties='Excel 12.0;HDR=Yes;'";
}
else if(constr == ".xls")
{
      constr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= '" + textBox1.Text + "';Extended Properties='Excel 4.0;HDR=Yes;'";
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900