需要按扩展名读取文件

本文关键字:读取 文件 扩展名 | 更新日期: 2023-09-27 18:28:33

我希望在列表视图中只读取一种文件类型,所以如果文件以.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;
        }

需要按扩展名读取文件

您可以使用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
}

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

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