2016-12-30 49 views
-1

我想將文本文件存儲在字符串數組中的文本文件中,並將其傳送到數據網格視圖表。有沒有什麼辦法可以做到這一點如何讀取文件夾中的多個texfile並將每個文本文件存儲在數組中C#

private string[] textfiles = Directory.GetFiles("D:\\UPLOADS", "*.txt") 
           .Select(Path.GetFileName) 
           .ToArray(); 

我用上面的方法來獲取文本文件。

for (int i = 0; i < excelfiles.Length; i++) 
     { 
      dt.Rows.Add(i, excelfiles[i], File.ReadAllText(textfiles[i]) , "24/12/16", "3.42pm", 837482, "Approve/Reject"); 
     } 

但是我得到以下錯誤。

Could not find file 'C:\Program Files (x86)\IIS Express\[2016-12-30] lololololol.xlsm(desc).txt'.

我的路徑表示爲d:\ UPLOADS

這裏是完整的代碼。

protected void Page_Load(object sender, EventArgs e) 
    { 

    } 

    private string[] excelfiles = Directory.GetFiles("D:\\UPLOADS", "*.xlsm") 
           .Select(Path.GetFileName) 
           .ToArray(); 
    private string[] textfiles = Directory.GetFiles("D:\\UPLOADS", "*.txt") 
           .Select(Path.GetFileName) 
           .ToArray(); 




    protected void btnSubmit_Click(object sender, EventArgs e) 
    { 
     GridView1_SelectedIndexChanged(sender, e); 
    } 

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     DataTable dt = new DataTable(); 
     dt.Columns.Add("ExcelID", typeof(int)); 
     dt.Columns.Add("excelName", typeof(string)); 
     dt.Columns.Add("excelDescription", typeof(string)); 
     dt.Columns.Add("date", typeof(string)); 
     dt.Columns.Add("time", typeof(string)); 
     dt.Columns.Add("empID", typeof(int)); 
     dt.Columns.Add("firstApproval", typeof(string)); 

     for (int i = 0; i < excelfiles.Length; i++) 
     { 
      dt.Rows.Add(i, excelfiles[i], File.ReadAllText(textfiles[i]) , "24/12/16", "3.42pm", 837482, "Approve/Reject"); 
     } 


     GridView1.DataSource = dt; 
     GridView1.DataBind(); 
    } 

感謝

+0

是的,有很多方法可以做到這一點。你有沒有嘗試做點什麼? – Steve

+0

請仔細閱讀:http://stackoverflow.com/help/how-to-ask – bit

回答

2

加載文本文件時,從整個文件名中刪除路徑D:\ UPLOADS。所以當你試圖讀取文件名的內容時,你沒有任何路徑給File.ReadAllText

這將強制該方法嘗試從當前進程目錄(... \ IIS Express ...)讀取哪裏沒有這樣的文件。

你需要一個路徑檢索您的文件的內容,所以你可以刪除的LINQ Select部分,只留下....

private string[] textfiles = Directory.GetFiles("D:\\UPLOADS", "*.txt"); 
1

有幾個API,您會發現在這種情況下,相關的。

Directory.GetFiles()返回文件夾中所有文件的完整路徑數組。

File.ReadAllText()以字符串形式返回文件的所有內容。

使用這兩個你應該是絕對能夠實現你所要求的功能。

相關問題