hi im working on a website in asp.net and i am a begginer in C#. i want to get rid of these nested IF statements ihave in the following function. can someone help me do this? thanks.

protected void btnUpload_Click(object sender, EventArgs e)  //upload file function
    {
        //Condition for fileupload
        if (Uploader.HasFile)
        {
            if (CheckFileType(Uploader.FileName))
            {
                if (Uploader.PostedFile.ContentLength > 1000 && Uploader.PostedFile.ContentLength < 10000)  //Maximum content length
                {
                    try 
                    {

                        string PathName = Server.MapPath("~/assets/uploads"); //get path name
                        string FileName = Uploader.FileName;
                        string FileSrc = Path.Combine(PathName, FileName);

                        //Disable Overwrite
                            if (File.Exists(FileSrc))   //File exists condition
                            {                           //Display Message
                            lblUploadResult.Text = "Error!: File " + FileName + " already exists. <br />";
                            lblUploadResult.ForeColor = System.Drawing.Color.White;
                            }
                            else //file does not exist condition
                            {
                            Uploader.SaveAs(FileSrc);
                            lblUploadResult.Text = "Result!: File " + FileName + " has uploaded successfully. <br />";
                            lblUploadResult.ForeColor = System.Drawing.Color.Green;
                            string[] FileInfo = { PathName, FileName, FileSrc };
                            Session["FILEINFO"] = FileInfo;
                        }
                    }
                    catch (Exception ex)    //exception trap
                    {
                        //display error message
                        lblUploadResult.Text = ex.Message;
                        lblUploadResult.ForeColor = System.Drawing.Color.Red;
                    }//catch
                }// if file size is in range
                else
                {
                    //display error message
                    lblUploadResult.Text = "Error!!!: There must be more than a 1000 characters and less that 10000 characters. <br />";
                    lblUploadResult.ForeColor = System.Drawing.Color.Red;
                }// if file size is out of range
            }//if checkfiletype returns true
            else
            {
                lblUploadResult.Text = "Error!!!: The file extentions that are allowed are: .txt, .log, .cfg, .doc, .docx. <br />";
                lblUploadResult.ForeColor = System.Drawing.Color.Red;
            }
        }//if (Uploader.HasFile)
        else
        {
            //display error message
            lblUploadResult.Text = "Error!!!: Please Upload Something. <br />";
            lblUploadResult.ForeColor = System.Drawing.Color.Red;
        }//ELSE condition for if uploader has a file
        Popuplate_DDL();
    }

Dani AI

Generated

Nice direction from — turning deep nesting into guard clauses flattens the flow and makes the happy path obvious. Beyond that, the next useful steps are to separate validation, saving, and UI updates into small methods, centralize configuration (allowed extensions, min/max sizes), and keep try/catch focused only around I/O.

A compact pattern that follows those ideas is: validate first (return a short error code), bail early on validation failures, then perform a single, well-scoped save operation and map result codes to UI text in one place. Example skeleton:

private string ValidateUpload(HttpPostedFile posted)
{
    if (posted == null || posted.ContentLength == 0)
        return "MISSING_FILE";          // caller maps codes to user text
    var ext = Path.GetExtension(posted.FileName)?.ToLowerInvariant();
    if (!AllowedExtensions.Contains(ext))
        return "BAD_EXTENSION";
    if (posted.ContentLength < MinBytes || posted.ContentLength > MaxBytes)
        return "BAD_SIZE";
    return null;
}

protected void btnUpload_Click(object sender, EventArgs e)
{
    var err = ValidateUpload(Uploader.PostedFile);
    if (err != null) { ShowErrorForCode(err); return; }

    try
    {
        var savedPath = SaveUploadSafe(Uploader.PostedFile); // Path.GetFileName + Path.Combine + SaveAs
        if (savedPath == null) { ShowErrorForCode("ALREADY_EXISTS"); return; }
        ShowSuccess(savedPath);
    }
    catch (IOException ex) { Log(ex); ShowErrorForCode("IO_ERROR"); }
}

Additional practical notes:

  • Use Path.GetFileName to avoid directory traversal and store files with safe names (GUID prefix or sanitized filename).
  • Verify type beyond extension (content signatures) and keep the allowed-extension list as a HashSet for O(1) checks.
  • Narrow try/catch blocks to I/O only and log exceptions; avoid storing raw file paths in Session — prefer a DB record or a stable identifier.
  • File uploads are a security risk; follow OWASP guidance.

References: the ASP.NET FileUpload control docs (FileUpload control), Path.GetFileName (Path.GetFileName), and OWASP notes on uploads (Unrestricted File Upload).

One esy way is to 'invert' the if like

protected void btnUpload_Click(object sender, EventArgs e)  //upload file function
    {
        //Condition for fileupload
        if (!Uploader.HasFile)
        {
            //display error message
            lblUploadResult.Text = "Error!!!: Please Upload Something. <br />";
            lblUploadResult.ForeColor = System.Drawing.Color.Red;
            Popuplate_DDL();
            return;
        }
        if (!CheckFileType(Uploader.FileName))
        {
            lblUploadResult.Text = "Error!!!: The file extentions that are allowed are: .txt, .log, .cfg, .doc, .docx. <br />";
            lblUploadResult.ForeColor = System.Drawing.Color.Red;
            Popuplate_DDL();
            return;
       }
       if (Uploader.PostedFile.ContentLength <= 1000 || Uploader.PostedFile.ContentLength >= 10000)  //Maximum content length
       {
            //display error message
            lblUploadResult.Text = "Error!!!: There must be more than a 1000 characters and less that 10000 characters. <br />";
            lblUploadResult.ForeColor = System.Drawing.Color.Red;
            Popuplate_DDL();
            return;
       }// if file size is out of range
       try 
       {
            string PathName = Server.MapPath("~/assets/uploads"); //get path name
            string FileName = Uploader.FileName;
            string FileSrc = Path.Combine(PathName, FileName);

            //Disable Overwrite
            if (File.Exists(FileSrc)) 
            { 
                //Display Message
                lblUploadResult.Text = "Error!: File " + FileName + " already exists. <br />";
                lblUploadResult.ForeColor = System.Drawing.Color.White;
                Popuplate_DDL();
                return;
            }
            Uploader.SaveAs(FileSrc);
            lblUploadResult.Text = "Result!: File " + FileName + " has uploaded successfully. <br />";
            lblUploadResult.ForeColor = System.Drawing.Color.Green;
            string[] FileInfo = { PathName, FileName, FileSrc };
            Session["FILEINFO"] = FileInfo;
       }
       catch (Exception ex)    //exception trap
       {
            //display error message
            lblUploadResult.Text = ex.Message;
            lblUploadResult.ForeColor = System.Drawing.Color.Red;
       }//catch
        Popuplate_DDL();
    }

I did not tested if I miss some thing, but there is the idea on how to.

JetBrains Resharper is an utility I use that helps a lot revamp your code.

Hope this helps

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.