VB.NET - 声明预期的编译错误

时间:2013-06-02 05:39:08

标签: asp.net vb.net file

我正在使用以下代码尝试写出我服务器根目录的images目录中的所有文件...但是我很难勉强让它为某些人工作,天知道为什么会这样。< / p>

这是我到目前为止的代码......

<%@ Import Namespace="System.IO" %>
<script language="vb" runat="server" explicit="true" strict="true">
Dim position As Integer

Public Sub GetFiles(ByVal path As String)
    If File.Exists(path) Then
        ' This path is a file 
        ProcessFile(path)
    ElseIf Directory.Exists(path) Then
        ' This path is a directory 
        ProcessDirectory(path)
    End If
End Sub

' Process all files in the directory passed in, recurse on any directories 
' that are found, and process the files they contain. 
Public Sub ProcessDirectory(ByVal targetDirectory As String)
    ' Process the list of files found in the directory. 
    Dim fileEntries As String() = Directory.GetFiles(targetDirectory)
    For Each fileName As String In fileEntries
        ProcessFile(fileName)
    Next

    ' Recurse into subdirectories of this directory. 
    Dim subdirectoryEntries As String() = Directory.GetDirectories(targetDirectory)
    For Each subdirectory As String In subdirectoryEntries
        ProcessDirectory(subdirectory)
    Next
End Sub

' Insert logic for processing found files here. 
Public Sub ProcessFile(ByVal path As String)
    Dim fi As New FileInfo(path)
    Response.Write("File Number " + position.ToString() + ". Path: " + path + " <br />")
    position += 1
End Sub

GetFiles("\images\")

</script>

我在以下代码行中收到声明预期的编译错误:

GetFiles("\images\")

我需要在这里宣布一些事情吗?我只是扯掉我的头发,在这个上秃头...... arggg!

1 个答案:

答案 0 :(得分:1)

内联脚本(意思是.aspx标记的一部分而不是后面的代码)只能包含方法,而不能包含命令。

虽然文档中未明确提及,但命名Code Declaration Blocks暗示它仅用于声明代码。您可以在其他地方或事件中调用该代码。

所以,你必须在页面事件中放置你想要执行的所有命令,在你的情况下,Page_Load看起来最合适:

Sub Page_Load(ByVal Sender As System.Object, ByVal e As System.EventArgs)
    GetFiles("\images\")
End Sub

如果您希望将其作为标记本身的一部分,那么您可以使用<% ... %>表示法,而不是将其放在<script>标记中,这会失败:

<!-- markup here -->
<!-- .... -->
<% GetFiles("\images\") %>