在FileDialog中获取文件名和文件扩展名 [英] To get File Name and Extension of File in FileDialog
本文介绍了在FileDialog中获取文件名和文件扩展名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我用一个代码用来打开一个文件并获取名称和File Extesion。在扩展的基础上,我需要更改连接字符串。以下是我正在做的代码..
OpenFileDialog fd = new OpenFileDialog();
fd.Title = 选择要上传的文件;
fd.Filter = Excel文件(* .xls)| * .xls | Excel文件(* xlsx )| * .xlsx;
if (fd.ShowDialog()== DialogResult.OK)
{
textBox1.Text = fd。 FileName.ToString();
string constr = 跨度>;
if (fd。) // code比较扩展名
{
constr = @ Provider = Microsoft.Jet。 OLEDB.12.0;数据源=' + textBox1.Text + ';扩展属性='Excel 12.0; HDR =是;'跨度>;
}
其他
如果()
{
constr = @ Provider = Microsoft.Jet.OLEDB.4.0; Data Source =' + textBox1.Text + ';扩展属性='Excel 4.0; HDR =是;' ;
}
解决方案
为此,您必须处理 FileOK [ ^ ]您的OpenFileDialog事件。在事件处理程序中,您可以使用 Path。 GetExtension [ ^ ]获取文件名的扩展名。
像这样使用..
if (fd.ShowDialog()== DialogResult.OK)
{
string str = fd.FileName;
string strExt = System.IO.Path.GetExtension(str);
if (strExt == .txt)
{
// do你的东西
}
else if (strExt == < span class =code-string> 。rtf)
{
// 做你的东西
}
if (System.IO.Path.GetExtension(fd.FileName)== 。xls)
}
}
else if (System.IO.Path.GetExtension(fd.FileName)== .doc)
{
}
.....
....
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..
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;'";
}
解决方案
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.
Use like this..
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 }
if(System.IO.Path.GetExtension(fd.FileName)==".xls") } } else if(System.IO.Path.GetExtension(fd.FileName)==".doc") { } ..... ....
这篇关于在FileDialog中获取文件名和文件扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文