[c# net4] Incorrect output for check existing file in upload in c# RRS feed

  • Question

  • User1872364149 posted

    Hi all, hope in your help.

    With this asp net page upload file in C# I need to check for duplicates.

    I accept 3 files in upload on the server.

    After uploading the new 3 files on the server, I have tried to upload the same file 3 files now existing on the server.

    For 3 files jpg existing on the server the response code on the Label is incorrect because is :

    File exist IMG0006A.jpg

    Instead that :

    File exist IMG0002A.jpg, IMG0005A.jpg, IMG0006A.jpg

    What's the problem ?

    Why if I have in the code foreach in Label the output is only for last existing file ?

    My code below, thank you in advance for any help.

    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;

    Friday, July 29, 2016 10:17 AM


  • User753101303 posted


    lblFileList.Text = "File exist " + Path.GetFileName(theFileName);

    changes ENTIRELY the existing text with the new value.

    Use lblFileList.Text += "value"; to append some text (this is a shortcut for lblFileList.Text = lblFileList.Text + "value";)

    Anyway I don't get the logic. It seems you are comparing a single name with names found in the directory so you'll always have a single match anyway (and with the earlier File.Exists test you do know already this file exists).

    My understanding would be rather that you want to loop on uploaded files to check if each file is already existing or not (File.Exists would enough, no need to check all files in the storage folder).
    Not enough info on the big picture but IMO using the original client side name to store files on your server is not always the best option (depending on how you want to handle name conflicts accross users or for a single user).

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, July 29, 2016 11:32 AM