FileSystemObject.CreateFolder 僅能建立單層目錄,父目錄不存在會失敗。需遞迴/迭代建立完整路徑。
<%
Function CreateFolderSingle(folderPath)
Dim fso
Set fso = Server.CreateObject("Scripting.FileSystemObject")
Dim absPath
absPath = Server.MapPath(folderPath)
If Not fso.FolderExists(absPath) Then
On Error Resume Next
fso.CreateFolder(absPath)
If Err.Number <> 0 Then
CreateFolderSingle = False
Err.Clear
Else
CreateFolderSingle = True
End If
On Error GoTo 0
Else
CreateFolderSingle = True ' 已存在視為成功
End If
Set fso = Nothing
End Function
%>
<%
Function CreateMultiFolder(relativePath)
Dim fso, absPath, parts, i, currentPath
Set fso = Server.CreateObject("Scripting.FileSystemObject")
' 統一路徑分隔符
relativePath = Replace(relativePath, "\", "/")
absPath = Server.MapPath(relativePath)
' 分割路徑層級
parts = Split(relativePath, "/")
currentPath = ""
For i = 0 To UBound(parts)
If parts(i) <> "" Then
currentPath = currentPath & parts(i) & "/"
Dim fullAbsPath
fullAbsPath = Server.MapPath(currentPath)
If Not fso.FolderExists(fullAbsPath) Then
On Error Resume Next
fso.CreateFolder(fullAbsPath)
If Err.Number <> 0 Then
CreateMultiFolder = False
Set fso = Nothing
Exit Function
End If
On Error GoTo 0
End If
End If
Next
CreateMultiFolder = True
Set fso = Nothing
End Function
' 使用範例
CreateMultiFolder "uploads/images/2024/01/15"
%>
<%
Sub ArrayFolder(path, sep)
Dim arr, part, newPath
arr = Split(path, sep)
newPath = ""
For Each part In arr
newPath = newPath & part & "/"
newPath = Replace(newPath, "//", "/")
CreateFolderSingle newPath ' 呼叫方法一
Next
End Sub
ArrayFolder "1/2/3", "/"
%>
<%
Function CreateDir(ByVal localPath)
On Error Resume Next
localPath = Replace(localPath, "\", "/")
Dim fso, parts, i, tmpPath, fullPath
Set fso = Server.CreateObject("Scripting.FileSystemObject")
parts = Split(localPath, "/")
For i = 0 To UBound(parts)
If i = 0 Then
tmpPath = parts(0) & "/"
Else
tmpPath = tmpPath & parts(i) & "/"
End If
fullPath = Left(tmpPath, Len(tmpPath) - 1) ' 移除尾部斜線
If Not fso.FolderExists(fullPath) Then
fso.CreateFolder fullPath
If Err.Number <> 0 Then
CreateDir = False
Err.Clear
Set fso = Nothing
Exit Function
End If
End If
Next
CreateDir = True
Set fso = Nothing
If Err.Number <> 0 Then
CreateDir = False
Err.Clear
End If
End Function
%>
fso.FolderExists 確認成功../../etc/passwd)Server.MapPath 快取減少重複呼叫On Error Resume Next 配合 Err.Number 檢查,避免拋出中斷流程掌握遞迴建立目錄邏輯,配合權限與安全防護,是 ASP 檔案上傳、快取、日誌等功能的基石。