I am trying to set up a page that will allow the user to browse a file directory on the Web server.
The aim is to allow users to drop files within a given directory structure and the code will create the tree view based off the directory.
When setting the Nodes Navigate URL it maps to the C:\Staging\Files which obvioulsy does not work on the web. I would need to map to http://webaddress/staging/files etc
Here is the offending code
Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
'
Dim rootDir As New DirectoryInfo("C:\Staging\")
' Enter the RecurseNodes function to recursively walk the directory tree.
Dim RootNode As TreeNode = RecurseNodes(rootDir)
' Add this Node hierarchy to the TreeNode control.
Treeview1.Nodes.Add(RootNode)
End If
End Sub
Private Function RecurseNodes(ByVal thisDir As DirectoryInfo) As TreeNode
Dim thisDirNode As New TreeNode(thisDir.Name, Nothing)
' Get all the subdirectories in this Directory.
Dim subDirs As DirectoryInfo() = thisDir.GetDirectories()
For Each subDir As DirectoryInfo In subDirs
thisDirNode.ChildNodes.Add(RecurseNodes(subDir))
Next
' Now get the files in this Directory.
Dim files As FileInfo() = thisDir.GetFiles()
For Each file As FileInfo In files
Dim thisFileNode As New TreeNode(file.Name, Nothing)
**thisFileNode.NavigateUrl = file.FullName**
thisDirNode.ChildNodes.Add(thisFileNode)
Next
Return thisDirNode
End Function
I think you should take the reverse approach. Rather than getting contents of a physical path on disk, try using Server.MapPath to grab contents of a virtual path combine it with a base URL:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim RootNode As TreeNode = RecurseNodes("~/files")
TreeView1.Nodes.Add(RootNode)
End If
End Sub
Private Overloads Function RecurseNodes(ByVal virtualPath As String) As TreeNode
If Not VirtualPathUtility.IsAbsolute(virtualPath) Then virtualPath = VirtualPathUtility.ToAbsolute(virtualPath)
virtualPath = VirtualPathUtility.RemoveTrailingSlash(virtualPath)
Dim baseUrl As String = Request.Url.GetLeftPart(UriPartial.Authority) + virtualPath
Return RecurseNodes(New DirectoryInfo(Server.MapPath(virtualPath)), baseUrl)
End Function
Private Overloads Function RecurseNodes(ByVal thisDir As DirectoryInfo, ByVal baseUrl As String) As TreeNode
Dim thisDirNode As New TreeNode(thisDir.Name, Nothing)
Dim subDirs As DirectoryInfo() = thisDir.GetDirectories()
For Each subDir As DirectoryInfo In subDirs
thisDirNode.ChildNodes.Add(RecurseNodes(subDir, baseUrl + subDir.Name + "/"))
Next
Dim files As FileInfo() = thisDir.GetFiles()
For Each file As FileInfo In files
Dim thisFileNode As New TreeNode(file.Name, Nothing)
thisFileNode.NavigateUrl = baseUrl + file.Name
thisDirNode.ChildNodes.Add(thisFileNode)
Next
Return thisDirNode
End Function
Related
I am trying to create a simple encryption program with visual basic on visual studio. My program is to encrypt an image then decrypt it. The system is saying that the request is not supported. As a note I am just learning about encrypting and not sure if I am even doing this correctly. Any comments or help would be much appreciated.
Error is from this: File.Encrypt(FileName)
if my encrypt is creating an error then my decrypt will most likely as well
Imports System
Imports System.IO
Imports System.Security.Cryptography
Partial Class _Default
Inherits System.Web.UI.Page
'My Encrypt button that takes the file from my FileUpload tool and Encrypts it, then outputs on my label
'that the file was successfully encrypted
Protected Sub EncryptButton_Click(sender As Object, e As EventArgs) Handles EncryptButton.Click
Dim FileName As String = FileUpload1.FileName
File.Encrypt(FileName)
Label1.Text = "Encrypt" + FileName
End Sub
'My Decrypt button that takes the file from my FileUpload tool and Encrypts it, then outputs on my label
'that the file was successfully encrypted
Protected Sub DecryptButton_Click(sender As Object, e As EventArgs) Handles DecryptButton.Click
Dim FileName As String = FileUpload1.FileName
File.Decrypt(FileName)
Label1.Text = "Decrypt" + FileName
End Sub
'Load page that will display a success output on the label if the upload is completed
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If FileUpload1.HasFile = True Then
Label1.Text = "Success"
Else
Label1.Text = "Failed"
End If
End Sub
Protected Sub CustomValidator1_ServerValidate(source As Object, args As ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
'Verify the control has a file
If Not FileUpload1.HasFile Then
CustomValidator1.ErrorMessage = "A file is required in order to proceed"
args.IsValid = False
Else
'next 2 lines are all one line
Dim ext As String =
System.Web.VirtualPathUtility.GetExtension(FileUpload1.FileName).ToUpper()
If Not ext = ".GIF" And Not ext = ".JPG" And Not ext = ".PNG" Then
'next 2 lines are all one line
CustomValidator1.ErrorMessage = String.Concat("Invalid file type '", ext, "' -must be .gif or .jpg or .png to continue")
args.IsValid = False
Else
args.IsValid = True
End If
End If
End Sub
End Class
I searched for "System.IO.IOException" and found Troubleshooting Exceptions: System.IO.IOException which states
Make sure the file and directory exist.
Then looking at the code:
Dim FileName As String = FileUpload1.FileName
I see that there is no directory specified for the file. So, you need to use Path.Combine so that you can give File.Encrypt the full filename including the path.
(There is no indiction in the posted code of which directory the uploaded file is in, so I can't help further with that. It could be that FileUpload1 has a property which gives that.)
I have file upload and upload link button and submit button .. so when i select file and click on upload then file name display in label and when i again click on browse file and select file and click on upload then file name again save in label so means multiple file name display in label i.e.
abc.docx
def.docx
.. and so on ..
now i try to save these files in database with different record means if these files save in database table then look like this
ID DocumentName DocumentPath
1 abc.docx /downloads/abc.docx
2 def.docx /files/def.docx
for this i try this
sp
alter procedure spupload_file
#DocumentName varchar(100),
#Doctype tinyint
as
insert into DocDownloads (DocumentID,DocumentName,DocType)
select (select max(DocumentID) from DocDownloads )+ROW_NUMBER() over(order by #DocumentName),#DocumentName,7
code
Protected Sub LinkButton1_Click(sender As Object, e As EventArgs) Handles LinkButton1.Click
uploadmultiple_file(fileUpEx.FileName)
End Sub
Public Sub uploadmultiple_file(filename As String)
If fileUpEx.HasFiles Then
For Each uploadedfile As HttpPostedFile In fileUpEx.PostedFiles
'Label4.Text = ("<b>File: </b>" + uploadedfile.FileName)
Label4.Text += String.Format("{0}<br />", uploadedfile.FileName)
Next
End If
End Sub
Protected Sub pb_Add_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles pb_submit.Click
Dim strKeyName() As String = {"DocumentName", "DocType"}
Dim objKeyVal() As Object = {Label4.Text,7}
structDb = objDataSet.ExecSP("tbl", "spupload_file", strKeyName, objKeyVal)
If structDb.intCode = 0 Then
Label5.Text = structDb.strMessage
Label5.CssClass = "error"
Exit Sub
End If
End Sub
when i try this ... this shows record in database table like
1 abc.docx<br />def.docx<br />
where as i want like this
1 abc.docx
2 def.docx
Index was outside the bounds of the array.
and how i insert also document path
any help ?
UPDATED
ok according to #Andy Reid
i try this
For Each file As HttpPostedFile In ListBox1.Items
Dim DocumentName As String = file.FileName
Dim strKeyName() As String = {"DocumentName", "DocType"}
Dim objKeyVal() As Object = {DocumentName, 7}
structDb = objDataSet.ExecSP("tbl", "spupload_file", strKeyName, objKeyVal)
Next
If structDb.intCode = 0 Then
Label5.Text = structDb.strMessage
Label5.CssClass = "error"
Exit Sub
End If
but this shows error
An exception of type 'System.InvalidCastException' occurred in DecibelCRM.dll but was not handled in user code
Additional information: Unable to cast object of type 'System.Web.UI.WebControls.ListItem' to type 'System.Web.HttpPostedFile'.
Using a listbox instead of the Label4, if dataset DocumentID is AutoIncrement
Protected Sub UploadLinkButton_Click(sender As Object, e As EventArgs) Handles UploadLinkButton.Click
uploadmultiple_file(FileUpEx.FileName)
End Sub
Public Sub uploadmultiple_file(filename As String)
If fileUpEx.HasFiles Then
'Add each PostedFile to list Box instead of using label
For Each uploadedfile As HttpPostedFile In fileUpEx.PostedFiles
FilesListBox.Items.Add(uploadedfile.FileName)
Next
End If
End Sub
Protected Sub pb_Add_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SubmitButton.Click
Dim objDataSet As New objDataSet 'Or whatever you have
Dim DocType as Integer = 7
'Gets each file from FilesListBox to insert them into objDataSet
For Each file As HttpPostedFile In FilesListBox.Items
Dim DocumentName as String = file.FileName
'Because the DocumentID is AutoIncrement, you don't need to enter it here
objDataSet.DocDownloads.AddDocDownloadsRow(DocumentName, DocType)
Next
End Sub
This will be for the data table, it should put each PostedFile as a new Row into DocDownloads. Upon doing some more research, the full path isn't accessible due to security reasons
Your code:
Public Sub uploadmultiple_file(filename As String)
If fileUpEx.HasFiles Then
For Each uploadedfile As HttpPostedFile In fileUpEx.PostedFiles
'Label4.Text = ("<b>File: </b>" + uploadedfile.FileName)
Label4.Text += String.Format("{0}<br />", uploadedfile.FileName)
Next
End If
End Sub
Try
Public Sub uploadmultiple_file(filename As String)
If fileUpEx.HasFiles Then
Try
For Each uploadedfile As HttpPostedFile In fileUpEx.PostedFiles
Label4.Text += uploadedfile.FileName & vbCRLF
'Possibly something like: "Label4.Text += uploadedfile.FullPath & vbCRLF" for the document path
Next
Catch ex as Exception
'Whatever exception handling code
End try
End If
End Sub
I'm trying to save an image to a local path (I'm not going to be deploying my project on a server) and I'm having difficulty with putting my finger on the correct path for the file upload:
Protected Sub htmleditorextender_ImageUploadComplete(sender As Object, e As AjaxControlToolkit.AjaxFileUploadEventArgs)
Dim fullpath = Request.MapPath("~/img/ar") & "/" & e.FileName
TextBox1_HtmlEditorExtender.AjaxFileUpload.SaveAs(fullpath)
e.PostedUrl = fullpath
End Sub
This doesn't work, and no image is uploaded to the said folder. What's going wrong?
try this
Protected Sub HTMLEditorExtender_ImageUploadComplete(sender As Object, e As AjaxControlToolkit.AjaxFileUploadEventArgs)
Dim fullpath As String = Server.MapPath("~/img/ar/") + e.FileName
HTMLEditorExtender.AjaxFileUpload.SaveAs(fullpath)
e.PostedUrl = Page.ResolveUrl(fullpath)
End Sub
I am a total beginner at VB.NET so you may need to bear with me but I need to edit this code behind so that a null value is passed to my database for the 'imageurl' field. The front end is a web form where a user can enter details of a book, with the option of uploading a book cover.
I want to change my code so that if the file upload dialog does not fulfil hasFile, the GUID string generated in the database will be a NULL value (this is so I can have a 'no image available' image using the NullImageUrl property in ASP.)
This is what I've tried to implement so far, but intellisense is telling me that "Value of type String cannot be converted to 'System.GUID'.
Code Behind:
Imports System.Data.OleDb
Partial Public Class addBook
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub btn_submission_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btn_submission.Click
Dim noFile As String = Nothing
Dim myGUID = Guid.NewGuid()
Dim newFileName As String = myGUID.ToString() & ".jpg"
Dim fileLocationOnServerHardDisk = Request.MapPath("img/thumb") & "/" & newFileName
If fu_picture.HasFile Then
fu_picture.SaveAs(fileLocationOnServerHardDisk)
Else
myGUID = noFile
End If
Dim oleDbConn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
Dim SqlString As String = "Insert into booklist(Title,Author,PublicationDate,Pages,Publisher,Blurb,imgurl,AverageRating)
Values (#f1,#f2,#f3,#f4,#f5,#f6,#f7,#f8)"
Dim cmd As OleDbCommand = New OleDbCommand(SqlString, oleDbConn)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#f1", tb_booktitle.Text)
cmd.Parameters.AddWithValue("#f2", tb_bookauthor.Text)
cmd.Parameters.AddWithValue("#f3", tb_bookpubyear.Text)
cmd.Parameters.AddWithValue("#f4", tb_bookpages.Text)
cmd.Parameters.AddWithValue("#f5", tb_publisher.Text)
cmd.Parameters.AddWithValue("#f6", tb_blurb.Text)
cmd.Parameters.AddWithValue("#f7", "img/thumb/" & newFileName)
cmd.Parameters.AddWithValue("#f8", rbl_Stars.SelectedValue)
oleDbConn.Open()
cmd.ExecuteNonQuery()
System.Threading.Thread.Sleep("2000")
Response.Redirect("~/addedrecord.aspx")
End Sub
Protected Sub rbl_Stars_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles rbl_Stars.SelectedIndexChanged
End Sub
End Class
Please tell me if I'm completely wrong in my line of thinking!
EDIT: At this present moment, even if a file is not uploaded, a guid string + jpg suffix are generated in the database table even if the image itself doesn't exist
You should pass DBNull.Value to your db if you fail the requirement
cmd.Parameters.AddWithValue("#f7", _
if(fu_picture.HasFile, "img/thumb/" & newFileName, DbNull.Value)
The ternary operator allows you to test the flag HasFile just when you create the parameter.
If it is false you set the parameter value to DBNull.Value. If HasFile is true you can build the correct path to your imagefile. Of course this removes the necessity to assign Nothing to myGuid in the code before.
I'm retrieveing the current path with:
Dim paths As String = HttpContext.Current.Request.FilePath
Which returns something like /VHP/hmo.aspx
What I need to narrow down is the FOLDER (VHP). How do I remove the / before it and the /filename after it?
Does this work for you?
Dim paths As String = HttpContext.Current.Request.FilePath
Dim dir as String= Path.GetDirectoryName(Server.MapPath(path))
UPDATE
According to your code, you should do this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim strFileNamePath As String = System.IO.Path.GetDirectoryName(Server.MapPath(HttpContext.Current.Request.FilePath))
''some how grab the working folder name here
If strFileNamePath = "xyz" Then
'do this
Else If strFileNamePath = "abc" then
'do this'
End If
End Sub
Notice how I changed HttpContext.Current.Request.Url.AbsolutePath for HttpContext.Current.Request.FilePath