2013-06-02 118 views
0

我正在使用下面的代碼嘗試寫出我的服務器根目錄的images目錄中的所有文件......但是我很失敗,無法讓它工作有些,天知道爲什麼會這樣。VB.NET - 聲明預期的編譯錯誤

這裏是我迄今爲止代碼...

<%@ 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!

+0

我懷疑它不喜歡你的字符串中額外的'\'。 – tinstaafl

回答

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\") %> 
+0

除了我想在.aspx文件中調用GetFiles()函數,通過if語句確定'<%If Request.ServerVariables(「QUERY_STRING」)=「id = 6566」然後%>'我需要這將被輸入到已經在頁面上的HTML ... –

+0

好吧,看看我的編輯。 –

+0

謝謝,這工作完美!真棒! –