2016-03-02 49 views
0

我想上傳多個文件,只是得到它們的文件名。 當我試圖做它只是上傳一個文件。多文件上傳,沒有完整路徑

所以它上傳文件的完整路徑(它的工作原理)。

private void bChooseFolder_Click(object sender, EventArgs e) 
{ 
    CoreClass.OPENDIALOG.Multiselect = true; 
    string oldFilter = CoreClass.OPENDIALOG.Filter; 
    CoreClass.OPENDIALOG.Filter = "(*.csv) | *.csv"; 

    if (CoreClass.OPENDIALOG.ShowDialog() == DialogResult.OK) 
     tbFolderPath.Text = string.Join(FileSeperator, CoreClass.OPENDIALOG.FileNames);// <-- this works, but here I get the full path 

    CoreClass.OPENDIALOG.Filter = oldFilter; 
    CoreClass.OPENDIALOG.Multiselect = false; 
} 

所以我得到的只是文件名,但它上傳只是一個文件:

private void bChooseFolder_Click(object sender, EventArgs e) 
{ 
    CoreClass.OPENDIALOG.Multiselect = true; 
    string oldFilter = CoreClass.OPENDIALOG.Filter; 
    CoreClass.OPENDIALOG.Filter = "(*.csv) | *.csv"; 

    if (CoreClass.OPENDIALOG.ShowDialog() == DialogResult.OK) 
     tbFolderPath.Text = string.Join(FileSeperator, System.IO.Path.GetFileNameWithoutExtension(CoreClass.OPENDIALOG.FileName)); // <-- Doesn't work. Just one File. 

    CoreClass.OPENDIALOG.Filter = oldFilter; 
    CoreClass.OPENDIALOG.Multiselect = false; 
} 

回答

1

OK,如果你正在開發WinForms應用程序,然後你使用OpenFileDialog其中包含2個屬性:

  • FileName獲取或設置一個字符串,其中包含文件對話框中選定的文件名。
  • FileNames獲取對話框中所有選定文件的文件名。

然後第一個將永遠不會包含幾個文件,你應該只在Multiselect = false;模式使用它。

如果你需要顯示在一個文本框中的所有文件名,那麼你可以使用String.Join方法和LINQ枚舉收集和不帶擴展名的每個元素獲取文件名:

if (CoreClass.OPENDIALOG.ShowDialog() == DialogResult.OK) 
    tbFolderPath.Text = string.Join(FileSeperator, CoreClass.OPENDIALOG.FileNames.Select(x => System.IO.Path.GetFileNameWithoutExtension(x)).ToArray()); // <-- Doesn't work. Just one File. 
+0

然後我得到一個錯誤:參數1 :無法將字符串[]轉換爲字符串 – Purger86

+0

@Tomi我擴展了我的答案 –

+1

哇這個工程太棒了!謝謝! – Purger86