0

I am new to asp.net I have upload file control in .aspx page it works fine. However, I want to delete previous uploaded file from directory if user uploaded a new file.

So this is the abstract code of my code behind file:

public partial class mypage : System.Web.UI.Page
{
   //I cannot access upload label control value here
    string lblValue = lbluploadFile.Text   //this global variable doesn't work

 protected void Page_Load(object sender, EventArgs e)
 {
   // I can access asp.net label control value in page load

   lbluploadFile.Text

 }

 protected void btnAttachment_Click(object sender, EventArgs e)
 {
  File.Delete(ConfigurationManager.AppSettings["UploadFolder"].ToString() + lblValue);
 }

}
Mian Almas
  • 174
  • 3
  • 11
shaadi
  • 161
  • 2
  • 4
  • 21
  • What have you tried that hasn't worked for you? – ProgrammingLlama Nov 15 '17 at 06:02
  • Whats the point of having a global variable for `label text` though you can directly access its `text` property anywhere in current web form. – mmushtaq Nov 15 '17 at 06:06
  • @john I cannot access upload control label property out of page load. This code is not working for me. – shaadi Nov 15 '17 at 06:15
  • @mmushtaq I need to delete file in button click event. – shaadi Nov 15 '17 at 06:16
  • https://stackoverflow.com/questions/16405816/delete-file-on-server – Jaydip Jadhav Nov 15 '17 at 06:24
  • You can access label text in button click event `File.Delete(ConfigurationManager.AppSettings["UploadFolder"].ToString() + lbluploadFile.Text);` – mmushtaq Nov 15 '17 at 06:33
  • When you are dealing with `path string`, it is good to use `System.IO.Path.Combine()` to concatenate path values e.g. `File.Delete(Path.Combine(ConfigurationManager.AppSettings["UploadFolder"]‌​.ToString(), lbluploadFile.Text));` – mmushtaq Nov 15 '17 at 06:35

1 Answers1

0

How to delete all files and folders in a directory?

you need to get file first with server path (physical path) then you can perform any operation like delete move or change meta data.

combine server path (directory) where you uploaded file with the name of file to get file.

if you need to upload new file in same folder and you want to delete previous one then shortest solution would be just upload new file with the previous name (considering you are uploading same mime type extension file again in case if name is different you can change to previous name) it will auto replace the previous file.

for Ref:How to: Copy, Delete, and Move Files and Folders

Mian Almas
  • 174
  • 3
  • 11
  • i don't want to delete all files instead i want to delete particular file which was uploaded previously. help with code if you can. – shaadi Nov 15 '17 at 06:28