ASP FileSystem
核对 Scripting.FileSystemObject 的创建与释放流程、Drives 集合属性、24 项文件/目录/路径操作方法及本地临时目录实测。
学完这一章,你能够
- 核对 Scripting.FileSystemObject 的创建与释放流程、Drives 集合属性、24 项文件/目录/路径操作方法及本地临时目录实测。
FileSystemObject 的定位与常见检查场景
`FileSystemObject`(简称 FSO)是 Classic ASP 访问服务器本地文件系统的核心 COM 对象。日常服务端脚本最常借助它判断指定文件、文件夹或磁盘驱动器是否存在,以及按路径提取驱动器名、父文件夹名、末端文件名、扩展名和不含扩展名的基名称。
创建文本文件示例与对象释放规范
除了查询文件系统元数据,`FileSystemObject` 还可直接创建、复制、移动与删除文件和目录。典型用法是先调用 `Server.CreateObject("Scripting.FileSystemObject")` 获取实例,再通过 `CreateTextFile("c:\test.txt", True)` 创建并覆盖文本文件,调用返回的 `TextStream` 的 `WriteLine` 写入 `"Hello World!"` 后执行 `Close`,并将对象变量设为 `Nothing` 及时释放 COM 引用。本地 CPython 3.12.14 离线验证脚本在 `tempfile.TemporaryDirectory()` 中实测了创建/追加/读取/删除文本文件、目录复制移动删除、8 项路径解析方法、`Drives`/特殊目录查询以及 `overwrite=False` 覆盖保护。
FileSystemObject 对象属性参考
| 属性 | 作用说明 |
|---|---|
| Drives | 返回包含本机所有可用驱动器(Drive 对象)的集合。 |
FileSystemObject 对象方法参考
| 方法 | 作用说明 |
|---|---|
| BuildPath | 在已有路径末尾按平台分隔符追加子名称并规范拼接。 |
| CopyFile | 将一个或多个文件从源路径复制到目标位置。 |
| CopyFolder | 递归复制一个或多个文件夹及其内容到目标路径。 |
| CreateFolder | 在指定路径创建新文件夹并返回对应的 Folder 对象。 |
| CreateTextFile | 创建文本文件(可控制是否覆盖)并返回用于读写的 TextStream 对象。 |
| DeleteFile | 删除一个或多个指定文件。 |
| DeleteFolder | 删除一个或多个指定文件夹及其内部内容。 |
| DriveExists | 检查指定的驱动器是否存在并返回布尔值。 |
| FileExists | 检查指定路径的文件是否存在并返回布尔值。 |
| FolderExists | 检查指定路径的文件夹是否存在并返回布尔值。 |
| GetAbsolutePathName | 基于当前工作目录将给定路径解析为从驱动器根起始的完整绝对路径。 |
| GetBaseName | 返回路径末端文件或文件夹去掉扩展名后的基名称。 |
| GetDrive | 返回与指定驱动器路径对应的 Drive 对象。 |
| GetDriveName | 提取指定路径字符串中的驱动器名称(如 C:)。 |
| GetExtensionName | 返回路径末端成分的文件扩展名(不含前导点号)。 |
| GetFile | 返回指向指定现有文件的 File 对象。 |
| GetFileName | 返回路径中最后一个成分的文件名或文件夹名。 |
| GetFolder | 返回指向指定现有目录的 Folder 对象。 |
| GetParentFolderName | 返回路径中最后一个成分的父目录路径。 |
| GetSpecialFolder | 按编号(0=Windows、1=System、2=Temporary)返回 Windows 特殊目录路径。 |
| GetTempName | 生成随机的临时文件或文件夹名称(仅返回名称,不自动创建文件)。 |
| MoveFile | 将一个或多个文件移动到新位置。 |
| MoveFolder | 将一个或多个文件夹移动到新位置。 |
| OpenTextFile | 按读(1)、写(2)或追加(8)模式打开文本文件并返回 TextStream 对象。 |
运行 FileSystemObject 临时目录文件/文件夹增删改查与路径解析离线验证
"""Offline Classic ASP FileSystemObject verification lab (IIS ASP absent)."""
import json
import ntpath
import os
from pathlib import Path
import shutil
import tempfile
class MockFileSystemObject:
"""Offline model of Scripting.FileSystemObject backed by a sandboxed directory."""
def __init__(self, sandbox_root: Path) -> None:
self.root = sandbox_root
self.drives = ["C:", "D:"]
@property
def Drives(self) -> list[str]:
return list(self.drives)
def BuildPath(self, base: str, name: str) -> str:
return ntpath.join(base, name)
def GetDriveName(self, path: str) -> str:
drive, _ = ntpath.splitdrive(path)
return drive
def GetParentFolderName(self, path: str) -> str:
trimmed = path.rstrip("\\/")
parent = ntpath.dirname(trimmed)
return parent
def GetFileName(self, path: str) -> str:
trimmed = path.rstrip("\\/")
return ntpath.basename(trimmed)
def GetExtensionName(self, path: str) -> str:
_, ext = ntpath.splitext(self.GetFileName(path))
return ext.lstrip(".")
def GetBaseName(self, path: str) -> str:
base, _ = ntpath.splitext(self.GetFileName(path))
return base
def GetAbsolutePathName(self, rel_path: str) -> str:
return str((self.root / rel_path).resolve())
def GetTempName(self, seq: int = 1) -> str:
return f"rad{seq:05X}.tmp"
def GetSpecialFolder(self, folder_spec: int) -> str:
mapping = {
0: r"C:\Windows",
1: r"C:\Windows\System32",
2: str(self.root / "temp"),
}
return mapping[folder_spec]
def DriveExists(self, drive_spec: str) -> bool:
norm = drive_spec.strip().rstrip("\\").upper()
if len(norm) == 1:
norm += ":"
return norm in self.drives
def FileExists(self, p: Path) -> bool:
return p.is_file()
def FolderExists(self, p: Path) -> bool:
return p.is_dir()
def CreateFolder(self, p: Path) -> Path:
p.mkdir(parents=False, exist_ok=False)
return p
def CreateTextFile(self, p: Path, overwrite: bool = True):
if p.exists() and not overwrite:
raise FileExistsError(str(p))
return p.open("w", encoding="utf-8", newline="\r\n")
def OpenTextFile(self, p: Path, iomode: int = 1, create: bool = False):
mode_map = {1: "r", 2: "w", 8: "a"}
if iomode == 1 and not p.exists():
if create:
p.touch()
else:
raise FileNotFoundError(str(p))
return p.open(mode_map[iomode], encoding="utf-8", newline="")
def CopyFile(self, src: Path, dst: Path) -> None:
shutil.copy2(src, dst)
def MoveFile(self, src: Path, dst: Path) -> None:
shutil.move(str(src), str(dst))
def DeleteFile(self, p: Path) -> None:
p.unlink()
def CopyFolder(self, src: Path, dst: Path) -> None:
shutil.copytree(src, dst)
def MoveFolder(self, src: Path, dst: Path) -> None:
shutil.move(str(src), str(dst))
def DeleteFolder(self, p: Path) -> None:
shutil.rmtree(p)
def main() -> None:
cases = []
with tempfile.TemporaryDirectory(prefix="asp_fso_") as tmp:
root = Path(tmp)
fso = MockFileSystemObject(root)
# Case 1: CreateTextFile + OpenTextFile + FileExists + DeleteFile
test_file = root / "test.txt"
with fso.CreateTextFile(test_file, overwrite=True) as fh:
fh.write("Hello World!\n")
exists_after_create = fso.FileExists(test_file)
with fso.OpenTextFile(test_file, iomode=8) as fh:
fh.write("Second Line\n")
with fso.OpenTextFile(test_file, iomode=1) as fh:
lines = fh.read().splitlines()
fso.DeleteFile(test_file)
exists_after_delete = fso.FileExists(test_file)
expected1 = {
"exists_after_create": True,
"lines": ["Hello World!", "Second Line"],
"exists_after_delete": False,
}
actual1 = {
"exists_after_create": exists_after_create,
"lines": lines,
"exists_after_delete": exists_after_delete,
}
cases.append({
"name": "fso_create_open_and_delete_text_file",
"summary": "Verify CreateTextFile, OpenTextFile (append/read), FileExists, and DeleteFile in temp dir.",
"expected": expected1,
"actual": actual1,
"passed": actual1 == expected1,
})
# Case 2: Folder & File copy/move/delete
src_dir = fso.CreateFolder(root / "src")
note = src_dir / "note.txt"
with fso.CreateTextFile(note, overwrite=True) as fh:
fh.write("ASP FSO")
copied_note = src_dir / "note_copy.txt"
fso.CopyFile(note, copied_note)
moved_note = src_dir / "note_moved.txt"
fso.MoveFile(copied_note, moved_note)
bak_dir = root / "bak"
fso.CopyFolder(src_dir, bak_dir)
archived_dir = root / "archived"
fso.MoveFolder(bak_dir, archived_dir)
archived_files = sorted(p.name for p in archived_dir.iterdir())
bak_exists_after_move = fso.FolderExists(bak_dir)
fso.DeleteFolder(archived_dir)
archived_exists_after_del = fso.FolderExists(archived_dir)
expected2 = {
"src_exists": True,
"archived_files": ["note.txt", "note_moved.txt"],
"bak_exists_after_move": False,
"archived_exists_after_del": False,
}
actual2 = {
"src_exists": fso.FolderExists(src_dir),
"archived_files": archived_files,
"bak_exists_after_move": bak_exists_after_move,
"archived_exists_after_del": archived_exists_after_del,
}
cases.append({
"name": "fso_folder_copy_move_delete",
"summary": "Verify CreateFolder, FolderExists, CopyFile, MoveFile, CopyFolder, MoveFolder, DeleteFolder.",
"expected": expected2,
"actual": actual2,
"passed": actual2 == expected2,
})
# Case 3: Path inspection helpers
sample_path = fso.BuildPath(r"C:\inetpub\wwwroot\demo", "report.asp")
expected3 = {
"built": r"C:\inetpub\wwwroot\demo\report.asp",
"drive_name": "C:",
"parent": r"C:\inetpub\wwwroot\demo",
"file_name": "report.asp",
"extension": "asp",
"base_name": "report",
"temp_name": "rad0002A.tmp",
}
actual3 = {
"built": sample_path,
"drive_name": fso.GetDriveName(sample_path),
"parent": fso.GetParentFolderName(sample_path),
"file_name": fso.GetFileName(sample_path),
"extension": fso.GetExtensionName(sample_path),
"base_name": fso.GetBaseName(sample_path),
"temp_name": fso.GetTempName(42),
}
cases.append({
"name": "fso_path_inspection_methods",
"summary": "Verify BuildPath, GetDriveName, GetParentFolderName, GetFileName, GetExtensionName, GetBaseName, GetTempName.",
"expected": expected3,
"actual": actual3,
"passed": actual3 == expected3,
})
# Case 4: Drives collection, DriveExists, GetSpecialFolder, GetAbsolutePathName
abs_note = fso.GetAbsolutePathName("src/note.txt")
expected4 = {
"drives": ["C:", "D:"],
"c_exists": True,
"z_exists": False,
"special_windows": r"C:\Windows",
"special_system": r"C:\Windows\System32",
"abs_ends_with_note": True,
}
actual4 = {
"drives": fso.Drives,
"c_exists": fso.DriveExists("c"),
"z_exists": fso.DriveExists("Z:"),
"special_windows": fso.GetSpecialFolder(0),
"special_system": fso.GetSpecialFolder(1),
"abs_ends_with_note": os.path.normpath(abs_note).endswith(os.path.join("src", "note.txt")),
}
cases.append({
"name": "fso_drives_and_special_folders",
"summary": "Verify Drives collection, DriveExists, GetSpecialFolder, and GetAbsolutePathName.",
"expected": expected4,
"actual": actual4,
"passed": actual4 == expected4,
})
# Case 5: CreateTextFile overwrite=False guard
guard_file = root / "locked.txt"
with fso.CreateTextFile(guard_file, overwrite=True) as fh:
fh.write("v1")
overwrite_blocked = False
try:
fso.CreateTextFile(guard_file, overwrite=False)
except FileExistsError:
overwrite_blocked = True
with fso.CreateTextFile(guard_file, overwrite=True) as fh:
fh.write("v2")
final_text = guard_file.read_text(encoding="utf-8")
expected5 = {"overwrite_blocked": True, "after_force_overwrite": "v2"}
actual5 = {"overwrite_blocked": overwrite_blocked, "after_force_overwrite": final_text}
cases.append({
"name": "fso_overwrite_protection_guard",
"summary": "Verify CreateTextFile raises when overwrite=False on existing file and replaces when True.",
"expected": expected5,
"actual": actual5,
"passed": actual5 == expected5,
})
print(json.dumps({
"version": "CPython 3.12.14 offline Classic ASP / VBScript verifier (IIS ASP absent)",
"cases": cases,
}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 验证 CreateTextFile/OpenTextFile/FileExists/DeleteFile、目录复制移动删除、8 项路径提取方法、Drives 与特殊目录查询以及 overwrite=False 保护。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:e84bce3e18aa40a5a5f011c958d7e026c3c3404c5a789150ed1ebdfced3e82d5
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:35aa1a89338d80db8583d6b00557d88daa6b6d1ef86db942a2a8ffbbe6e4ee3c
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
FileSystemObject 的 GetBaseName、GetFileName 和 GetExtensionName 对路径 C:\demo\report.asp 分别返回什么结果?
展开参考解答
GetFileName 返回 report.asp,GetBaseName 返回不含扩展名的 report,GetExtensionName 返回不含点号的 asp。