2017-02-13 41 views
1

我最初有一個Fileupload工具來上傳文本文件,操縱其內容並顯示到列表框或文本框中。然而,限制是Fileupload僅支持單個上傳,至少對於我正在使用的.Net Framework版本。在按鈕單擊並顯示內容時讀取多個文本文件

我打算做的只是使用按鈕控件並刪除Fileupload。點擊按鈕後,我需要讀取指定文件夾路徑內的文本文件,然後首先顯示多行文本框內的內容。 (不僅僅是文件名)這是我的書面代碼,它不起作用。

protected void btnGetFiles_Click(object sender, EventArgs e) 
     { 
      string content = string.Empty; 
      DirectoryInfo dinfo = new DirectoryInfo(@"C:\samplePath"); 
      FileInfo[] Files = dinfo.GetFiles("*.txt"); 



      foreach (FileInfo file in Files) 
      { 
       //ListBox1.Items.Add(file.Name); 
       content += content; 

      } 
      txtContent.Text = content; 


     } 
+0

只是一個FYI,.NET框架與多個文件上傳無關。這是純粹的客戶端/ IIS工作。要看看如何允許多個文件上傳,看看[這個SO問題](http://stackoverflow.com/questions/17441925/how-to-choose-multiple-files-using-file-upload-control) – Icemanind

+0

因爲我紅色的某處Fileupload工具可以在最新版本中具有multipleUpload功能。感謝雖然修正 – rickyProgrammer

回答

1

因爲你的是基於web的應用程序,你不能訪問像c:\\..這樣的物理路徑,所以你應該使用Server.MapPath(根據註釋,你不需要使用Server.MapPath獲取文件)。然後爲了獲得內容,你可以嘗試如下:

protected void btnGetFiles_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      StringBuilder content = new StringBuilder(); 
      if (Directory.Exists(@"C:\samplePath")) 
      { 
       // Execute this if the directory exists 
       foreach (string file in Directory.GetFiles(@"C:\samplePath","*.txt")) 
       { 
        // Iterates through the files of type txt in the directories 
        content.Append(File.ReadAllText(file)); // gives you the conent 
       } 
       txtContent.Text = content.ToString(); 
      } 
     } 
     catch 
     { 
      txtContent.Text = "Something went wrong"; 
     } 

    } 
+0

實際上先生,該應用程序現在用於本地使用,因此,如果我正在使用絕對路徑。當前的代碼實際上可以找到路徑,唯一的問題是隻有文件的內容沒有被讀取。只有文件名。當我嘗試代碼時,預計我有一個虛擬路徑必須被編碼的錯誤。 – rickyProgrammer

+0

@rickyProgrammer:好的,然後繼續用'C:\ samplePath''代替'Server.MapPath(「相對路徑在這裏)」並檢查它是否工作;查看更新後的代碼 –

+0

感謝如果我喜歡它在gridview中顯示? – rickyProgrammer

0

你寫了content += content;,就是這個問題。將其更改爲content += file.Name;,它將起作用。

+0

仍然沒有輸出先生。 – rickyProgrammer

+0

對不起,你是正確的在那裏,但它顯示的文件名,我如何顯示每個文件的內容 – rickyProgrammer

+0

有一個非常好的示例如何從https:// msdn中的.txt文件中讀取文本.microsoft.com/en-us/library/db5x7c0d(v = vs.110).aspx –

相關問題