我正在尋找只讀一個文件類型到我的列表視圖,所以如果文件以.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;
}
什麼是你的問題?您沒有爲您發佈的代碼提供任何解釋。代碼中存在一些問題嗎?它是什麼?哪裏?你有沒有做過任何調試? – tnw
我的問題是如何做到這一點:)我使用循環像....如果(Path.Fileextesion ==「.txt」) –
對不起,我真的不知道如何使用這個網站,我是一個新手,代碼很好,只有當我點擊加載文件按鈕它讀取.txt文件罰款,然後它讀取字符的Excel文件,我想要它讀取文件的擴展名,所以如果文件以.txt結尾它只會讀取該文件進入列表視圖,謝謝 –