Upload & Download Files to web server using ASP.NET v1.1 and VB.NET

I need to be able to upload files to my web server.  I then would like to be able to download these files and delete them as well.  Please help!
azyet24Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Jason ScolaroCommented:
Hi azyet24,

Here's a good article on File Uploading:  http://www.codeproject.com/aspnet/fileupload.asp

There are a variety of ways to allow downloading.  You can either use a hyperlink that points to the the file (assuming the file location is within the web application's directory structure) or you could get as complicated as using the Reponse.WriteFile method.  

To delete a file you simply use the System.IO.File class.  System.IO.File.Delete("c:\inetpub\wwwroot\appName\filename.ext")

Hopefully that helps you get started.

-- Jason

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
5thcavCommented:
you want this done via a web page right? Sounds like you want an FTP program like wsftp or FlashFXP
it this is the case use serv-u ftp and simply point to the site, all uploads and downloads are fully managed from the UI..



azyet24Author Commented:
HI Jason,

I have the files to upload and download, but I'm not sure how to delete the files.  Can you look at this and see if you can help?

index.aspx:

<script runat="server">

    Dim currentDir As String
    Dim directorySeparatorChar As Char = Path.DirectorySeparatorChar
   
   
    Sub Page_Load(sender As Object, e As EventArgs)
   
       Dim root As String = "d:\hshome\harvestc\harvestchurchofgod.com\Members\Admin\Documents\Data"
       Dim thisPage As String = Request.Path
   
       currentDir = Request.Params("dir")
       If currentDir Is Nothing Then
         currentDir = root
       End If
       If Not currentDir.StartsWith(root) Then
         currentDir = root
       End If
   
       Dim sb As New StringBuilder(4096)
   
       If Not currentDir.Equals(Root) Then
         ' not at the root
         Dim currentDirParent As String
         Dim lastIndex As Integer = _
           currentDir.LastIndexOf(directorySeparatorChar)
         If lastIndex <> -1 Then
           currentDirParent = currentDir.Substring(0, lastIndex)
         Else
           currentDirParent = currentDir
         End If
         sb.Append("<a href=").Append(thisPage)
         sb.Append("?dir=").Append(Server.UrlEncode(currentDirParent))
         sb.Append("><img width=30 border=0 src=images/Up.gif></a><br>")
       End If
   
       DoUpload()
   
       sb.Append("<br><img border=0 src=images/OpenFolder.gif>&nbsp;")
       sb.Append("<font face=verdana>")
       sb.Append(currentDir)
       sb.Append("</font>")
       sb.Append("<br>")
   
       sb.Append("<table>")
       sb.Append("<tr bgcolor=#D8D8D8>")
       sb.Append("<td width=200><font face=verdana size=3>Name</font></td>")
       sb.Append("<td><font face=verdana size=3>Type</font></td>")
       sb.Append("<td><font face=verdana size=3>Size</font></td>")
       sb.Append("<td><font face=verdana size=3>Modified</font></td>")
       sb.Append("</tr>")
   
     Dim dirs() As String
       Try
         dirs = Directory.GetDirectories(currentDir)
   
         Dim d As String
         For Each d In dirs
           Dim dirName As String = Path.GetFileName(d)
           sb.Append("<tr>")
           sb.Append("<td><img src=images/Folder.gif>&nbsp;")
           sb.Append("<a href=").Append(thisPage)
           sb.Append("?dir=").Append(Server.UrlEncode(currentDir))
           sb.Append(directorySeparatorChar)
           sb.Append(Server.UrlEncode(dirName))
           sb.Append(">").Append(dirName).Append("</a>")
           sb.Append("</td>")
           sb.Append("<td><font face=verdana size=2>folder</font></td>")
           sb.Append("<td>&nbsp;</td>")
           sb.Append("<td><font face=verdana size=2>")
           sb.Append(Directory.GetLastWriteTime(currentDir & _
             directorySeparatorChar.ToString() & dirName).ToString())
           sb.Append("</font></td>")
           sb.Append("</tr>")
     
         Next
   
       Catch ex As Exception
       End Try
       
       Try
         Dim dirInfo As New DirectoryInfo(currentDir)
         Dim files() As FileInfo
         files = dirInfo.GetFiles()
   
         Dim f As FileInfo
         For Each f In files
           Dim filename As String = f.Name
           sb.Append("<tr>")
           sb.Append("<td><img src=images/File.gif>&nbsp;")
           sb.Append("<a href=FileDownload.aspx?file=")
           sb.Append(Server.UrlEncode(currentDir))
           sb.Append(directorySeparatorChar)
           sb.Append(Server.UrlEncode(filename))
           sb.Append(">").Append(filename).Append("</a>")
           sb.Append("</td>")
           sb.Append("<td><font face=verdana size=2>file</font></td>")
           sb.Append("<td><font face=verdana size=2>")
           sb.Append(f.Length.ToString())
           sb.Append("</font></td>")
           sb.Append("<td><font face=verdana size=2>")
           sb.Append(File.GetLastWriteTime(currentDir & _
             directorySeparatorChar.ToString() & f.Name).ToString())
           sb.Append("</font></td>")
           sb.Append("</tr>")
         Next
       Catch ex As Exception
       End Try
   
       sb.Append("</table>")
      dirContent.Text = sb.ToString()
    End Sub
   
   
    Sub DoUpload()
   
       If Not (uploadedFile.PostedFile Is Nothing) Then
         Try
           Dim postedFile = uploadedFile.PostedFile
           Dim filename As String = Path.GetFileName(postedFile.FileName)
           Dim contentType As String = postedFile.ContentType
           Dim contentLength As Integer = postedFile.ContentLength
           postedFile.SaveAs(currentDir & _
             directorySeparatorChar.ToString() & filename)
         Catch ex As Exception
           message.Text = "Failed uploading file"
         End Try
       End If
    End Sub

</script>


.....



    <form enctype="multipart/form-data" runat="server">
       <asp:Label id="dirContent" runat="server"></asp:Label><asp:Label id="message" runat="server"></asp:Label>
        <p>
      <hr />
            <%-- File Upload --%><font face="verdana">Select File to Upload:</font>
            <input id="uploadedFile" type="file" runat="server" />
            <input id="upload" type="button" value="Upload" runat="server" onserverclick="Page_Load" />
        </p>
        <p>
        </p>
        <p>
        </p>
        <p>
        </p>
    </form>
PMI ACP® Project Management

Prepare for the PMI Agile Certified Practitioner (PMI-ACP)® exam, which formally recognizes your knowledge of agile principles and your skill with agile techniques.

5thcavCommented:
here is how you can remove the files in a folder :)

DelFilesInDir(root)

'remove all files in folder
Sub DelFilesInDir(ByVal path As String)
try
        Dim dir As System.IO.DirectoryInfo
        dir = New System.IO.DirectoryInfo(path)

        Dim files As System.IO.FileInfo() = dir.GetFiles()

        For Each file As System.IO.FileInfo In files
         System.IO.File.Delete(file.Name)
        Next
catch
'file must be in use or deleated by another user
end try

    End Sub
azyet24Author Commented:
Question: DelFilesInDir(root) is giving me an error b/c it's not declared.  Also, how should I call this in the body so that it associates with the correct file?

5thcavCommented:
move this line and put it above the page load

 Dim root As String = "d:\hshome\harvestc\harvestchurchofgod.com\Members\Admin\Documents\Data"

or DelFilesInDir("d:\hshome\harvestc\harvestchurchofgod.com\Members\Admin\Documents\Data")
or DelFilesInDir("d:\hshome\harvestc\harvestchurchofgod.com\Members\Admin\Documents\Data\")

do you want to deleate the files after the user downloads them? or all the files in the folder..

If you could explain your usage in a real world scenario we would have a better idea
azyet24Author Commented:
Ok, I want to upload files as need to this directory.  Then download these files at will.  I'd like to have a "Delete" added to each file so that I can delete a file when I want to, not the entire directory and not when the file is downloaded.  What do I need to do to this code?  Thanks

<script runat="server">

    Dim currentDir As String
    Dim directorySeparatorChar As Char = Path.DirectorySeparatorChar
   
   
    Sub Page_Load(sender As Object, e As EventArgs)
   
       Dim root As String = "d:\hshome\harvestc\harvestchurchofgod.com\Members\Admin\Documents\Data"
       Dim thisPage As String = Request.Path
   
       currentDir = Request.Params("dir")
       If currentDir Is Nothing Then
         currentDir = root
       End If
       If Not currentDir.StartsWith(root) Then
         currentDir = root
       End If
   
       Dim sb As New StringBuilder(4096)
   
       If Not currentDir.Equals(Root) Then
         ' not at the root
         Dim currentDirParent As String
         Dim lastIndex As Integer = _
           currentDir.LastIndexOf(directorySeparatorChar)
         If lastIndex <> -1 Then
           currentDirParent = currentDir.Substring(0, lastIndex)
         Else
           currentDirParent = currentDir
         End If
         sb.Append("<a href=").Append(thisPage)
         sb.Append("?dir=").Append(Server.UrlEncode(currentDirParent))
         sb.Append("><img width=30 border=0 src=images/Up.gif></a><br>")
       End If
   
       DoUpload()
   
       sb.Append("<br><img border=0 src=images/OpenFolder.gif>&nbsp;")
       sb.Append("<font face=verdana>")
       'sb.Append(currentDir)
       sb.Append("</font>")
       sb.Append("<br>")
   
       sb.Append("<table>")
       sb.Append("<tr bgcolor=#D8D8D8>")
       sb.Append("<td width=200><font face=verdana size=3>Name</font></td>")
       sb.Append("<td><font face=verdana size=3>Type</font></td>")
       sb.Append("<td><font face=verdana size=3>Size (Kb)</font></td>")
       sb.Append("<td><font face=verdana size=3>Modified</font></td>")
       sb.Append("</tr>")
   
     Dim dirs() As String
       Try
         dirs = Directory.GetDirectories(currentDir)
   
         Dim d As String
         For Each d In dirs
           Dim dirName As String = Path.GetFileName(d)
           sb.Append("<tr>")
           sb.Append("<td><img src=images/Folder.gif>&nbsp;")
           sb.Append("<a href=").Append(thisPage)
           sb.Append("?dir=").Append(Server.UrlEncode(currentDir))
           sb.Append(directorySeparatorChar)
           sb.Append(Server.UrlEncode(dirName))
           sb.Append(">").Append(dirName).Append("</a>")
           sb.Append("</td>")
           sb.Append("<td><font face=verdana size=2>folder</font></td>")
           sb.Append("<td>&nbsp;</td>")
           sb.Append("<td><font face=verdana size=2>")
           sb.Append(Directory.GetLastWriteTime(currentDir & _
             directorySeparatorChar.ToString() & dirName).ToString())
           sb.Append("</font></td>")
           sb.Append("</tr>")
     
         Next
   
       Catch ex As Exception
       End Try
       
       Try
         Dim dirInfo As New DirectoryInfo(currentDir)
         Dim files() As FileInfo
         files = dirInfo.GetFiles()
   
         Dim f As FileInfo
         For Each f In files
           Dim filename As String = f.Name
           sb.Append("<tr>")
           sb.Append("<td><img src=images/File.gif>&nbsp;")
           sb.Append("<a href=FileDownload.aspx?file=")
           sb.Append(Server.UrlEncode(currentDir))
           sb.Append(directorySeparatorChar)
           sb.Append(Server.UrlEncode(filename))
           sb.Append(">").Append(filename).Append("</a>")
           sb.Append("</td>")
           sb.Append("<td><font face=verdana size=2>file</font></td>")
           sb.Append("<td><font face=verdana size=2>")
           sb.Append(f.Length.ToString() / 1000)
           sb.Append("</font></td>")
           sb.Append("<td><font face=verdana size=2>")
           sb.Append(File.GetLastWriteTime(currentDir & _
             directorySeparatorChar.ToString() & f.Name).ToString())
           sb.Append("</font></td>")
               sb.Append("<td>")
               sb.Append("</td>")
           sb.Append("</tr>")
               DelFilesInDir(root)
         Next
       Catch ex As Exception
       End Try
   
       sb.Append("</table>")
      dirContent.Text = sb.ToString()
    End Sub
   
   
    Sub DoUpload()
   
       If Not (uploadedFile.PostedFile Is Nothing) Then
         Try
           Dim postedFile = uploadedFile.PostedFile
           Dim filename As String = Path.GetFileName(postedFile.FileName)
           Dim contentType As String = postedFile.ContentType
           Dim contentLength As Integer = postedFile.ContentLength
           postedFile.SaveAs(currentDir & _
             directorySeparatorChar.ToString() & filename)
         Catch ex As Exception
           message.Text = "Failed uploading file"
         End Try
       End If
    End Sub

   

      'remove all files in folder
      Sub DelFilesInDir(ByVal path As String)
            try
              Dim dir As System.IO.DirectoryInfo
               dir = New System.IO.DirectoryInfo(path)

              Dim files As System.IO.FileInfo() = dir.GetFiles()

              For Each file As System.IO.FileInfo In files
               System.IO.File.Delete(file.Name)
              Next
            catch
            'file must be in use or deleated by another user
            end try

    End Sub

</script>
Jason ScolaroCommented:
azyet24,

Simply use the System.IO.File.Delete method.  It takes one argument, the path and filename of the file you want to delete.

I don't know how you want to call that line, whether it's from a button click event, or you have a DataGrid full of files and you can select your file that way...

But, just as an example... let's use a QueryString with 1 parameter, filepath.

Dim strFilePath As String = Request.QueryString("filepath")
System.IO.File.Delete(strFilePath)

If you put that code in your Page_Load and went to the page by typing this in your address bar, it would delete the specified file:
http://path.to.your.site/Default.aspx?filepath=c:\inetpub\wwwroot\filename.ext

This is assuming the appropriate permissions are in place.  Obviously you need to tweak this for your scenario.  Hopefully this gives you some insight on how to do what you need.

-- Jason
azyet24Author Commented:
Jason,

This requires that I specify ahead of time the file that I want to delete, right?  Using the code I posted, is there a way to just Append the text "Delete" and when I click on this it will delete that file?

Bobby
Jason ScolaroCommented:
azyet24,

I'm not sure what kind of control dirContent is but you could use it to add a LinkButton control that does the work for you...

This would go in your For Each f in files Loop:

Dim lb As New LinkButton
lb.Text = "Delete " & filename
lb.CommandArgument = f.FullName
AddHandler lb.Command, AddressOf LinkButton_Command
dirContent.Controls.Add(lb)

Then create a new Sub:
Public Sub LinkButton_Command(sender As Object, e As CommandEventArgs)
    System.IO.File.Delete(e.CommandArgument)
End Sub

-- Jason
azyet24Author Commented:
How do I get this to show up on my page?  I entered your code but I don't see the delete text.  I'm guessing I need to add Appends to it, but don't know how.

       Try
         Dim dirInfo As New DirectoryInfo(currentDir)
         Dim files() As FileInfo
         files = dirInfo.GetFiles()
   
         Dim f As FileInfo
         For Each f In files
           Dim filename As String = f.Name
           sb.Append("<tr>")
           sb.Append("<td><img src=images/File.gif>&nbsp;")
           sb.Append("<a href=FileDownload.aspx?file=")
           sb.Append(Server.UrlEncode(currentDir))
           sb.Append(directorySeparatorChar)
           sb.Append(Server.UrlEncode(filename))
           sb.Append(">").Append(filename).Append("</a>")
           sb.Append("</td>")
           sb.Append("<td><font face=verdana size=2>file</font></td>")
           sb.Append("<td><font face=verdana size=2>")
           sb.Append(f.Length.ToString() / 1000)
           sb.Append("</font></td>")
           sb.Append("<td><font face=verdana size=2>")
           sb.Append(File.GetLastWriteTime(currentDir & _
             directorySeparatorChar.ToString() & f.Name).ToString())
           sb.Append("</font></td>")
               sb.Append("<td>")
               sb.Append("</td>")
           sb.Append("</tr>")
             
              Dim lb As New LinkButton
                  lb.Text = "Delete " & filename
                  lb.CommandArgument = f.FullName
                  AddHandler lb.Command, AddressOf LinkButton_Command
                  dirContent.Controls.Add(lb)
         
             Next
       Catch ex As Exception
       End Try

------
    Public Sub LinkButton_Command(sender As Object, e As CommandEventArgs)
    System.IO.File.Delete(e.CommandArgument)
      End Sub
Jason ScolaroCommented:
azyet24, is your For Each f in files Loop running?  You don't need the Append logic, that is the way of classic ASP.  With ASP.NET you should utilize server controls and add them to your Controls collection.  

In the code I gave you above we are creating a LinkButton server control and adding it to the page via the dirContent control, which I don't know what that is.  It might be a good idea to put a placeholder control on the page and use that for your Delete text.

<asp:PlaceHolder id="phDeletes" runat="server" />

This allows you to place the dynamic content anywhere on the page you like.

-- Jason
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.