Monday, April 7, 2008

Multiple file upload in ASP.NET

Protected Sub btnattachsiteplan_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnattachsiteplan.ClickDim usersession As myApp.UserSessionusersession = Session("UserSession")lbluploadsiteplan.Text = ""Dim uname As String = usersession.UserNameDim path As String = "temp\Siteplan\" + uname + "\"Dim appPath As String = Request.PhysicalApplicationPathIf FileUpload2.HasFile ThenIf Not Directory.Exists(appPath + path) ThenDirectory.CreateDirectory(appPath + path)End IfDim savePath As String = appPath + path + Server.HtmlEncode(FileUpload2.FileName)FileUpload2.SaveAs(savePath)Dim dt As DataTable = New DataTabledt.Rows.Clear()dt.Columns.Add("Attachment", GetType(String))Dim dr As DataRowdr = dt.NewRowdr("Attachment") = FileUpload2.PostedFile.FileNamedt.Rows.Add(dr)GridView2.DataSource = dtGridView2.DataBind()dt.Rows.Clear()lbluploadsiteplan.Text = "File Attached"Elselbluploadsiteplan.Text = "Browse a File and then Click Attach"End IfEnd SubDeleting uploaded files from the temporary folderProtected Sub btndeletesiteplan_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btndeletesiteplan.Clicklbluploadsiteplan.Text = ""Dim usersession As myApp.UserSessionuserSession = Session("UserSession")Dim uname As String = userSession.UserNameTryDim path1 As String = Server.MapPath("~\temp\Siteplan\" + uname)If Directory.Exists(path1) ThenDim s As StringFor Each s In System.IO.Directory.GetFiles(path1)System.IO.File.Delete(s)Next sEnd Iflbluploadsiteplan.Text = "Files Deleted"Dim dt As DataTable = New DataTableGridView2.DataSource = dtGridView2.DataBind()Catchlbluploadsiteplan.Text = "Select a File and then Click Delete"End TryEnd SubSaving files from the temporary folderProtected Sub SaveFilesFromTemporaryFolderDim uname as myApp.UserSession.UserNameTryDim path1 As String = Server.MapPath("~/temp/ExtraPages/" + uname + "/")Dim path2 As String = Server.MapPath("~/Uploads/ExtraPages/" + maxcrplankey.ToString() + "/")If Not Directory.Exists(path2) ThenDirectory.CreateDirectory(path2)End IfDim diSource As DirectoryInfo = New DirectoryInfo(path1)Dim diTarget As DirectoryInfo = New DirectoryInfo(path2)For Each fi As FileInfo In diSource.GetFiles()fi.CopyTo(Path.Combine(diTarget.ToString(), fi.Name), True)fi.Delete()Nextlbluploadpage.Text = ""CatchEnd TryTryDim path3 As String = Server.MapPath("~/temp/Siteplan/" + uname + "/")Dim path4 As String = Server.MapPath("~/Uploads/Siteplan/" + maxcrplankey.ToString() + "/")If Not Directory.Exists(path4) ThenDirectory.CreateDirectory(path4)End IfDim diSource1 As DirectoryInfo = New DirectoryInfo(path3)Dim diTarget1 As DirectoryInfo = New DirectoryInfo(path4)For Each fi As FileInfo In diSource1.GetFiles()fi.CopyTo(Path.Combine(diTarget1.ToString(), fi.Name), True)fi.Delete()Nextlbluploadsiteplan.Text = ""CatchEnd TryEnd Sub

No comments: