2

I am developing a complaint form. In this this form, I must make a function that uploads a file and then delete the file that was uploaded. I can upload a file to the server, but I can't take a link of the file I upload to the server in order to delete it. Please help me. Here is my code:

public string FilePath;
protected void btAdd_Click(object sender, EventArgs e)
    {          
    if (AttachFile.HasFile)
        {
            try
            {
                    string[] sizes = {"B", "KB", "MB", "GB"};
                    double sizeinbytes = AttachFile.FileBytes.Length;
                    string filename = Path.GetFileNameWithoutExtension(AttachFile.FileName);
                    string fileextension = Path.GetExtension(AttachFile.FileName);
                    int order = 0;
                    while (sizeinbytes >= 1024 && order + 1 < sizes.Length)
                    {
                        order++;
                        sizeinbytes = sizeinbytes/1024;
                    }
                    string result = String.Format("{0:0.##} {1}", sizeinbytes, sizes[order]);
                    string encryptionFileName = EncrytionString(10);                       
                    FilePath = "Path" + encryptionFileName.Trim() + AttachFile.FileName.Trim();
                    AttachFile.SaveAs(FilePath);                    
            }
            catch (Exception ex)
            {
                lbMessage.Visible = true;
                lbMessage.Text = ex.Message;
            }
        }
    } 

protected void btDelete_Click(object sender, EventArgs e)
    {
        try
        {
            File file = new FileInfo(FilePath);
            if (file.Exists)
            {
                File.Delete(FilePath);
            }
        }
        catch (FileNotFoundException fe)
        {
            lbMessage.Text = fe.Message;
        }
        catch (Exception ex)
        {
            lbMessage.Text = ex.Message;
        }
    }
Erik Schierboom
  • 16,301
  • 10
  • 64
  • 81
Tung
  • 61
  • 1
  • 7
  • 1
    Can you be more specific when the problem occurs? I assume when the `btDelete_Click` method is called, it doesn't work, but can you post the exception that you get? – Erik Schierboom Apr 08 '13 at 06:49

2 Answers2

1

Each request in asp.net creates a new object of your Page.
If you set variables during one request, they will not be available on the next request.

Your delete logic seems to depend upon FilePath being set during upload. If you want the page to remember that, keep it in the ViewState. The ViewState is maintained across requests to the same page and that would allow you to use the variable FilePath during delete.

This can be easily achieved by making FilePath a property and getting it from the ViewState.

public string FilePath
{
  get
  {
    return (string) ViewState["FilePath"];
  }
  set
  {
    ViewState["FilePath"] = value;
  }
}
nunespascal
  • 17,584
  • 2
  • 43
  • 46
  • 1
    nunespascal Would it be a solid solution to use a viewstate in placxe of database? – NiNaD PaNDyA Apr 08 '13 at 07:25
  • @NiNaDPaNDyA you definitely don't want to use a database until user input is complete. The delete button provided here I assume is to allow the user to correct the input file before finally saving all inputs. Saving the path to the db is part of the business logic of the application. – nunespascal Apr 08 '13 at 08:15
  • 2
    Bro then no need to use variables also just set the hasfile property of fileupload control to false. no more logic required. – NiNaD PaNDyA Apr 08 '13 at 08:28
  • No. Your are wrong on that one. `HasFile` is set only on the PostBack when the file is received. The file is not sent on every PostBack. Clicking of the delete button would be different PostBack. – nunespascal Apr 08 '13 at 08:42
  • 1
    Yup you are right but no need to do anything there is a browse button in file upload control if you want to change file then just click on that button select a new file and you are done with it... Not a single line of code required. – NiNaD PaNDyA Apr 08 '13 at 08:58
  • No. Since the file is saved to disk on `btAdd_Click`, if you don't delete it, you will have an extra file left lingering there. – nunespascal Apr 08 '13 at 09:07
  • 2
    Dont save file on btnadd _Click. just let it to be saved on submit btn's click event. – NiNaD PaNDyA Apr 08 '13 at 09:18
  • If only all business logic could be written on the click of one button, the world would be a merrier place! – nunespascal Apr 08 '13 at 09:29
  • 2
    you can do what ever you want to do... I am managing whole blog module Without using a single state variable as well as java script or Jquery – NiNaD PaNDyA Apr 08 '13 at 09:32
0

YOU SHOULD DO IT IN THIS WAY.

if (imgUpload.HasFile)
     {
                String strFileName = imgUpload.PostedFile.FileName;
                imgUpload.PostedFile.SaveAs(Server.MapPath("\\DesktopModules\\Indies\\FormPost\\img\\") + strFileName);
                SqlCommand cmd01 = new SqlCommand("insert into img (FeaturedImg) Values (@img)", cn01);
                    cmd01.Parameters.AddWithValue("@img", ("\\DesktopModules\\Indies\\FormPost\\img\\") + strFileName);
      }

With this code you can upload file in a particular location in your sites root directory. and the path will be stored in database as string. so you can access the file just by using the path stored in database. If you cant understand anything. or wanna know more u can contact me or ask me here in comments.

NiNaD PaNDyA
  • 197
  • 3
  • 15