我正在尝试设置一个页面,允许用户浏览Web服务器上的文件目录。
目的是允许用户删除给定目录结构中的文件,代码将根据目录创建树视图。
设置Nodes Navigate URL时,它会映射到C:\ Staging \ Files,这些文件无法在Web上运行。我需要映射到http://webaddress/staging/files等
以下是有问题的代码
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
答案 0 :(得分:1)
我认为你应该采取相反的方法。不要在磁盘上获取物理路径的内容,而是尝试使用Server.MapPath
获取虚拟路径的内容,并将其与基本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