2016-02-24 19 views
1

我使用多個文件上傳,我想每個文件名與全局數組分配使用foreach我怎麼能做到這一點的asp.net/c#叫img我如何分配全局陣列中的每個文件名?

string[] img={""}; 

foreach (string s in Request.Files) { 
    HttpPostedFile file = Request.Files[s]; 
    int fileSizeInBytes = file.ContentLength; 
    string fileName = file.FileName; 
    string fileExtension = ""; 

    if (!string.IsNullOrEmpty(fileName)) { 
     fileExtension = Path.GetExtension(fileName); 
     file.SaveAs(filename); 
    } 
} 

回答

2

我會用這個目的List<string>

List<string> img = new List<string>(); 

foreach (string s in Request.Files) 
{ 
    HttpPostedFile file = Request.Files[s]; 
    int fileSizeInBytes = file.ContentLength; 
    string fileName = file.FileName; 
    string fileExtension = ""; 

    if (!string.IsNullOrEmpty(fileName)) 
    { 
     img.add(fileName); 
     fileExtension = Path.GetExtension(fileName); 
     file.SaveAs(filename); 
    } 

這是爲什麼List<T>幾乎總是比在C#中使用array更好的一個很好的解釋:https://softwareengineering.stackexchange.com/a/221897

如果你給我們對你想要完成的事情有一個更好的解釋,我可以改進這個答案。

+0

謝謝你,我有包含IMG1,IMG2,IMG3和IMG4我想圖像的路徑插入到這些列IMG1,IMG2等使用LINQ to SQL的一個項目表,所以我決定分配在陣列中的每個路徑然後分配與LINQ數組索引 –

+0

您可以在列表獲得通過索引項以同樣的方式,你可以在一個陣列。只需簡單地使用:int myFirstImg = img [0]; – Ageonix

+0

感謝,但是當INT myFirstImg = IMG [0];它表明這個錯誤System.ArgumentOutOfRangeException –

相關問題