ASP:NET File Upload check if exist

coerrace
coerrace used Ask the Experts™
on
Hello I have this routine to upload files with ASP.NET:
       String savePath = @"C:\inetpub\wwwroot\esp\docstemp1_1\";

         if (FileUpload1_1.HasFile)
        {

            string FileExtention = System.IO.Path.GetExtension(FileUpload1_1.FileName);
            if (FileExtention == ".pdf")
            {
           
                String fileName = FileUpload1_1.FileName;

                savePath += fileName;


     
                FileUpload1_1.SaveAs(savePath);

     

                pdfdocumento1_1.Text = "All fine";

   
            }

            else
            {
                pdfdocumento1_1.Text = "Is not .pdf. ";

            }

Now what I need to add and wehre to check if the new upload already exist on the dir to avoid overwrtie?
Thank you
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2009

Commented:
if(System.IO.File.Exists(savePath))
   throw new Exception(...);
Try this:

As mrjoltcola suggested, you can check the existance of file at:
======================================================
String savePath = @"C:\inetpub\wwwroot\esp\docstemp1_1\";

         if (FileUpload1_1.HasFile)
        {
            string FileExtention = System.IO.Path.GetExtension(FileUpload1_1.FileName);
            if (FileExtention == ".pdf")
            {
                String fileName = FileUpload1_1.FileName;
                savePath += fileName;

                if(System.IO.File.Exists(savePath))
                       throw new Exception(...); //File already exists


                FileUpload1_1.SaveAs(savePath);
                pdfdocumento1_1.Text = "All fine";
            }
            else
            {
                pdfdocumento1_1.Text = "Is not .pdf. ";
            }

Author

Commented:
And in case exist how can i stop continue the script and return to request again the upload, colud yo clarify only a little the throw excpetion.
Thank you
Starting with Angular 5

Learn the essential features and functions of the popular JavaScript framework for building mobile, desktop and web applications.

Author

Commented:
to be more clear whatbhappen if the system ask if wan to overwrite yes or no if yes overwrite if no end and return.
Thank you
Top Expert 2009

Commented:
The system wont ask you that. You have to put that logic in yourself.

Author

Commented:
I know the system don't do that but applied on my code an specific code of a logic what can be?
Thank you
Top Expert 2009

Commented:
I don't understand.
Commented:
You can check the full sample from Micrososft for a nice formatted code

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.fileupload.saveas.aspx
<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>FileUpload.SaveAs Method Example</title>
<script runat="server">

    protected void  UploadButton_Click(object sender, EventArgs e)
    {
        // Before attempting to save the file, verify
        // that the FileUpload control contains a file.
        if (FileUpload1.HasFile) 
          // Call a helper method routine to save the file.
          SaveFile(FileUpload1.PostedFile);
        else
          // Notify the user that a file was not uploaded.
          UploadStatusLabel.Text = "You did not specify a file to upload.";
    }

      void SaveFile(HttpPostedFile file)
      {            
        // Specify the path to save the uploaded file to.
        string savePath = "c:\\temp\\uploads\\";

        // Get the name of the file to upload.
        string fileName = FileUpload1.FileName;

        // Create the path and file name to check for duplicates.
        string pathToCheck = savePath + fileName;

        // Create a temporary file name to use for checking duplicates.
        string tempfileName = "";

        // Check to see if a file already exists with the
        // same name as the file to upload.        
        if (System.IO.File.Exists(pathToCheck)) 
        {
          int counter = 2;
          while (System.IO.File.Exists(pathToCheck))
          {
            // if a file with this name already exists,
            // prefix the filename with a number.
            tempfileName = counter.ToString() + fileName;
            pathToCheck = savePath + tempfileName;
            counter ++;
          }

          fileName = tempfileName;

          // Notify the user that the file name was changed.
          UploadStatusLabel.Text = "A file with the same name already exists." + 
              "<br />Your file was saved as " + fileName;
        }
        else
        {
          // Notify the user that the file was saved successfully.
          UploadStatusLabel.Text = "Your file was uploaded successfully.";
        }

        // Append the name of the file to upload to the path.
        savePath += fileName;

        // Call the SaveAs method to save the uploaded
        // file to the specified directory.
        FileUpload1.SaveAs(savePath);

      }

</script>

</head>
<body>

    <h3>FileUpload.SaveAs Method Example</h3>

    <form id="Form1" runat="server">

        <h4>Select a file to upload:</h4>

        <asp:FileUpload id="FileUpload1"                 
            runat="server">
        </asp:FileUpload>

        <br /><br />

        <asp:Button id="UploadButton" 
            Text="Upload file"
            OnClick="UploadButton_Click"
            runat="server">
        </asp:Button>      

        <hr />

        <asp:Label id="UploadStatusLabel"
            runat="server">
        </asp:Label>   

    </form>

</body>
</html>

Open in new window

Well in my above code, you can do it by this way:

if(System.IO.File.Exists(savePath))
{
    lblErrorMessage.Text = "File already exists!";
    return;    
}

You can do one thing, place a checkbox near file upload control to ask user to overwrite existing image.

So, in condition you can check,

if(chkOverwrite.Checked == False && System.IO.File.Exists(savePath))
{
    lblErrorMessage.Text = "File already exists! Do you want to overwrite?";
    return;    
}
//else it will overwrite it

Let me know if u have any difficulty.

Author

Commented:
Excellent that´s what I need. Thank you for all!!!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial