-1

我希望只将一种文件类型读取到我的列表视图中,因此如果文件以 .txt 结尾,它应该只读取 .txt 文件,对于 csv 和 excel 文件也是如此。

    public void doexcel()
    {
        OleDbConnection cnn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + textBox_Choose.Text +
                              ";Extended Properties='Excel 12.0 XML;HDR=YES;';");

        string name; name = "";
        OleDbCommand oconn = new OleDbCommand("SELECT * from [" + "Sheet1$" + "]", cnn);
        cnn.Open();
        OleDbDataAdapter adp = new OleDbDataAdapter(oconn);
        DataTable dt = new DataTable();
        adp.Fill(dt);
        foreach (DataRow row in dt.Rows)
        {
            ListViewItem item = new ListViewItem(row[0].ToString());
            for (int i = 1; i < dt.Columns.Count; i++)
            {
                item.SubItems.Add(row[i].ToString());
            }
            listView1.Items.Add(item);
        }
    }




    public void dotxt()
    {

        string filepath = textBox_Choose.Text;
        FileStream yaNew = File.Open(filepath, FileMode.Open, FileAccess.Read);
        StreamReader yaRead = new StreamReader(yaNew);
        string yaView = yaRead.ReadToEnd();


        yaRead.Close();
        yaNew.Close();
        String[] yaArray = yaView.Split(new char[] { '\n' });
        foreach (string ya in yaArray)
        {
            listView1.Items.Add(ya);
        }

    }        


    private void button_Choose_Click(object sender, EventArgs e)
    {
        //Call the OpenFileDialog Object and name it 
        OpenFileDialog explore = new OpenFileDialog();

        //Set the directory path 
        explore.InitialDirectory = @"c:\MyProject";

        //set the file types 
        explore.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
        explore.FilterIndex = 2;
        explore.RestoreDirectory = true;


        //show result in the textbox 
        if (explore.ShowDialog() == DialogResult.OK)
        {
            textBox_Choose.Text = explore.FileName;
        }
4

2 回答 2

2

您可以使用 System.IO.Path.GetExtension 查看文件的扩展名

在您的代码中,它将是:

string extension = System.IO.Path.GetExtension(textBox_Choose.Text);
if (extension == ".txt")
    dotxt();
else if(extension == ".csv")
    doexcel();
else
{
    //deal with an unexpected case
}
于 2013-08-21T15:48:56.103 回答
0

您可以使用此代码获得扩展并执行您的逻辑

string ext = fileName.Substring(fileName.LastIndexOf('.'));

于 2013-08-21T15:38:43.087 回答