2016-07-29 23 views
-1

在C#中的這個asp網頁上傳文件,我需要檢查重複。錯誤的輸出檢查現有文件上傳在C#

我接受服務器上傳的3個文件。

enter image description here

上傳服務器上的新的3個文件後,我曾嘗試上傳同一文件3個文件現在現有的服務器上。在服務器上

對於3 JPG文件上存在Label響應代碼不正確,因爲是:

文件存在IMG0006A.jpg

而且不

文件存在IMG0002A.jpg,IMG0005A.jpg,IMG0006A.jpg

什麼問題?

爲什麼如果我在代碼foreachLabel輸出只是爲最後現有的文件?

我的代碼如下,預先感謝您的任何幫助。

if (File.Exists(theFileName)) 
{ 
    objDir = new DirectoryInfo(Server.MapPath("\\images\\)); 
    objFI = objDir.GetFiles("*.*"); 
    iFileCnt = 0; 

    if (objFI.Length > 0) 
    { 
     foreach (FileInfo file in objFI) 
     { 
      if (file.Name.ToString() == Path.GetFileName(theFileName)) 
      { 
       lblFileList.Text = "File exist " + Path.GetFileName(theFileName); 
       iFileCnt += 1; 
      } 
     } 
    } 
} 
+0

你不**添加**文本到標籤。你**在每次迭代中設置**。 –

+0

@ J.Steen謝謝,我很抱歉,但我不明白你的建議;文件重複時如何在網頁上打印? –

+2

您在每個foreach循環中覆蓋標籤的值。你沒有加入它。相反,找出一種方法來做到這一點。 –

回答

1

除了喬納森的答案。他正在檢查一個文件名,即文件名。您應該遍歷所有三個文件: 假設fileNames是您的三個文件名的列表。

int iFileCount = 0; 
foreach (string fileName in fileNames) 
{ 
    if (!System.IO.File.Exists(fileName)) continue; 

    if(iFileCount <= 0) 
    { 
     lblFileList.Text = "File exist " + System.IO.Path.GetFileName(fileName); 
    } 
    else 
    { 
     lblFileList.Text += ", " + System.IO.Path.GetFileName(fileName); 
    } 
    ++iFileCount; 
} 
0

嘗試

 if (File.Exists(theFileName)) 
     { 
      objDir = new DirectoryInfo(Server.MapPath("\\images\\)); 
      objFI = objDir.GetFiles("*.*"); 

      if (objFI.Length > 0) 
      { 
       foreach (FileInfo file in objFI) 
       { 
        if (file.Name.ToString() == Path.GetFileName(theFileName)) 
        { 
         if (iFileCnt == 0) 
         { 
          lblFileList.Text = "File exist " + Path.GetFileName(theFileName); 
         } 
         else 
         { 
          lblFileList.Text += ", " + Path.GetFileName(theFileName); 

         } 
         iFileCnt += 1; 
        } 
       } 
      } 
     } 

注意iFileCnt = 0需要被先前設置,否則每一個新的文件爲0。
如果我理解你正確地做什麼,但是,它會最好先獲得現有文件的列表,而不是每次刷新它。您只需要將每個成功的文件添加到FileInfo數組中,以確保列表完整。

+0

謝謝,但'Label'中的輸出沒有改變,只有最後一個重複的文件。 –

+0

你可以發佈更完整的提取物嗎? – 2016-07-29 12:05:01