ASP Folder
核对 Scripting.Folder 对象的实例化方式、Files 与 SubFolders 集合、13 项目录属性(含 IsRootFolder 与递归 Size)及 4 项目录操作方法。
学完这一章,你能够
- 核对 Scripting.Folder 对象的实例化方式、Files 与 SubFolders 集合、13 项目录属性(含 IsRootFolder 与递归 Size)及 4 项目录操作方法。
Folder 对象的获取与目录元数据查询
`Folder` 对象用于描述并操作服务器上的目录结构。需要先创建 `FileSystemObject`,再通过 `fs.GetFolder("c:\test")` 实例化 `Folder` 对象,随后即可读取 `fo.DateCreated` 等属性并在使用完毕后释放对象引用。
`Folder` 对象按成员类别分为集合(`Files`、`SubFolders`)、属性(13 项,包含 `IsRootFolder` 根目录判定与递归统计子项字节总和的 `Size`)以及方法(`Copy`、`Delete`、`Move`、`CreateTextFile`)。注意参考资料中偶有将 `IsRootFolder` 的布尔返回值拼写为 `ture`,实际标准返回值为 `True` 或 `False`。本地 CPython 3.12.14 离线验证脚本已在临时目录树中完整验证了 `Files`/`SubFolders` 集合、递归 `Size`、`IsRootFolder` 真假分支、目录复制/重命名/移动/删除以及 `Folder.CreateTextFile`。
Folder 对象集合参考
| 集合 | 作用说明 |
|---|---|
| Files | 返回当前文件夹内所有直接子文件组成的 Files 集合。 |
| SubFolders | 返回当前文件夹内所有直接子文件夹组成的 Folders 集合。 |
Folder 对象属性参考
| 属性 | 作用说明 |
|---|---|
| Attributes | 读取或设置文件夹属性位掩码(目录位为 16)。 |
| DateCreated | 返回文件夹的创建日期与时间。 |
| DateLastAccessed | 返回文件夹最后被访问的日期与时间。 |
| DateLastModified | 返回文件夹最后被修改的日期与时间。 |
| Drive | 返回文件夹所在磁盘驱动器的盘符字母。 |
| IsRootFolder | 若当前文件夹为驱动器根目录则返回 True,否则返回 False。 |
| Name | 读取或设置文件夹名称(赋值可实现目录重命名)。 |
| ParentFolder | 返回当前文件夹的上级父 Folder 对象(根目录无父目录)。 |
| Path | 返回文件夹的完整路径。 |
| ShortName | 返回遵循 8.3 命名约定的短文件夹名。 |
| ShortPath | 返回遵循 8.3 命名约定的短路径。 |
| Size | 递归汇总该文件夹内所有文件及子文件夹内容的总字节数。 |
| Type | 返回文件夹类型描述字符串(如 File Folder)。 |
Folder 对象方法参考
| 方法 | 作用说明 |
|---|---|
| Copy | 将当前文件夹及全部内容递归复制到指定目标位置。 |
| Delete | 删除当前文件夹及其包含的全部子项。 |
| Move | 将当前文件夹移动到指定目标路径。 |
| CreateTextFile | 在当前文件夹下直接创建新文本文件并返回 TextStream 对象。 |
运行 Folder 集合枚举、递归 Size、IsRootFolder 判定与目录增删改离线验证
"""Offline Classic ASP Folder object verification lab (IIS ASP absent)."""
from datetime import datetime, timezone
import json
from pathlib import Path
import shutil
import tempfile
def derive_short_folder(name: str) -> str:
clean = "".join(ch for ch in name.upper() if ch.isalnum())
return clean if len(clean) <= 8 else clean[:6] + "~1"
class MockFolder:
"""Offline model of Scripting.Folder backed by a real temporary directory."""
def __init__(self, path: Path, attributes: int = 16) -> None:
self._path = path
self._attributes = attributes
@property
def Files(self) -> list[str]:
return sorted(p.name for p in self._path.iterdir() if p.is_file())
@property
def SubFolders(self) -> list[str]:
return sorted(p.name for p in self._path.iterdir() if p.is_dir())
@property
def Attributes(self) -> int:
return self._attributes
@Attributes.setter
def Attributes(self, value: int) -> None:
self._attributes = value
@property
def DateCreated(self) -> str:
return datetime.fromtimestamp(self._path.stat().st_ctime, tz=timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
@property
def DateLastAccessed(self) -> str:
return datetime.fromtimestamp(self._path.stat().st_atime, tz=timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
@property
def DateLastModified(self) -> str:
return datetime.fromtimestamp(self._path.stat().st_mtime, tz=timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
@property
def Drive(self) -> str:
return self._path.drive.upper() or "C:"
@property
def IsRootFolder(self) -> bool:
return self._path == self._path.parent
@property
def Name(self) -> str:
return self._path.name
@Name.setter
def Name(self, new_name: str) -> None:
target = self._path.with_name(new_name)
self._path.rename(target)
self._path = target
@property
def ParentFolder(self) -> str:
return str(self._path.parent)
@property
def Path(self) -> str:
return str(self._path)
@property
def ShortName(self) -> str:
return derive_short_folder(self._path.name)
@property
def ShortPath(self) -> str:
return str(self._path.parent / self.ShortName)
@property
def Size(self) -> int:
return sum(p.stat().st_size for p in self._path.rglob("*") if p.is_file())
@property
def Type(self) -> str:
return "File Folder"
def Copy(self, destination: Path) -> "MockFolder":
shutil.copytree(self._path, destination)
return MockFolder(destination, self._attributes)
def Move(self, destination: Path) -> None:
shutil.move(str(self._path), str(destination))
self._path = destination
def Delete(self) -> None:
shutil.rmtree(self._path)
def CreateTextFile(self, filename: str, overwrite: bool = True):
target = self._path / filename
if target.exists() and not overwrite:
raise FileExistsError(str(target))
return target.open("w", encoding="utf-8", newline="\r\n")
def main() -> None:
cases = []
with tempfile.TemporaryDirectory(prefix="asp_folder_") as tmp:
root = Path(tmp)
work = root / "SampleProjectFolder"
work.mkdir()
(work / "a.txt").write_bytes(b"12345")
(work / "b.txt").write_bytes(b"1234567890")
sub = work / "nested"
sub.mkdir()
(sub / "c.txt").write_bytes(b"123")
fo = MockFolder(work)
# Case 1: Collections (Files, SubFolders), recursive Size, timestamps
expected1 = {
"files": ["a.txt", "b.txt"],
"subfolders": ["nested"],
"recursive_size": 18,
"has_timestamps": True,
}
actual1 = {
"files": fo.Files,
"subfolders": fo.SubFolders,
"recursive_size": fo.Size,
"has_timestamps": all(len(t) == 19 for t in (fo.DateCreated, fo.DateLastAccessed, fo.DateLastModified)),
}
cases.append({
"name": "folder_collections_size_timestamps",
"summary": "Verify Folder.Files, Folder.SubFolders, recursive Folder.Size, and timestamps.",
"expected": expected1,
"actual": actual1,
"passed": actual1 == expected1,
})
# Case 2: Identity, IsRootFolder, Attributes, ShortName/ShortPath, Type
anchor_folder = MockFolder(Path(root.anchor))
expected2 = {
"name": "SampleProjectFolder",
"is_root_subdir": False,
"is_root_anchor": True,
"attributes": 16,
"short_name": "SAMPLE~1",
"type": "File Folder",
"parent_matches": True,
}
actual2 = {
"name": fo.Name,
"is_root_subdir": fo.IsRootFolder,
"is_root_anchor": anchor_folder.IsRootFolder,
"attributes": fo.Attributes,
"short_name": fo.ShortName,
"type": fo.Type,
"parent_matches": fo.ParentFolder == str(root),
}
cases.append({
"name": "folder_identity_and_root_check",
"summary": "Verify Name, IsRootFolder (True for root, False for subdir), Attributes, ShortName, Type.",
"expected": expected2,
"actual": actual2,
"passed": actual2 == expected2,
})
# Case 3: Folder Copy, Move, Rename, Delete
copied = fo.Copy(root / "copied_proj")
copied.Name = "renamed_proj"
moved_target = root / "moved_proj"
copied.Move(moved_target)
moved_files = copied.Files
copied.Delete()
expected3 = {
"moved_files": ["a.txt", "b.txt"],
"deleted_cleanly": True,
"source_preserved": True,
}
actual3 = {
"moved_files": moved_files,
"deleted_cleanly": not moved_target.exists(),
"source_preserved": work.is_dir(),
}
cases.append({
"name": "folder_copy_move_delete",
"summary": "Verify Folder.Copy, Folder.Name rename, Folder.Move, and recursive Folder.Delete.",
"expected": expected3,
"actual": actual3,
"passed": actual3 == expected3,
})
# Case 4: Folder.CreateTextFile
with fo.CreateTextFile("index.asp", overwrite=True) as fh:
fh.write("<% Response.Write(\"OK\") %>")
expected4 = {
"files_after_create": ["a.txt", "b.txt", "index.asp"],
"content": "<% Response.Write(\"OK\") %>",
}
actual4 = {
"files_after_create": fo.Files,
"content": (work / "index.asp").read_text(encoding="utf-8"),
}
cases.append({
"name": "folder_create_textfile",
"summary": "Verify Folder.CreateTextFile creates a file directly inside the folder and updates Files.",
"expected": expected4,
"actual": actual4,
"passed": actual4 == expected4,
})
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()
- 验证 Files/SubFolders 集合与递归 Size=18 字节、IsRootFolder 对子目录返回 False 而对根返回 True、Copy/Rename/Move/Delete 以及 Folder.CreateTextFile。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:84697318154658eb377987f8a1fc49f4574b06865ccb1a316b6c466676e9b82c
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:a46a70b3116f7ca44e77f775848b68ccc9624e882745df36e3849062f396c889
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
Folder.Size 与 File.Size 的计算范围有何不同?对根目录访问 ParentFolder 会有什么限制?
展开参考解答
File.Size 仅统计单个文件的字节数,而 Folder.Size 会递归累加该目录及所有子目录内文件的总字节数;当 Folder.IsRootFolder 为 True 时,该目录已位于驱动器最顶层,不再存在有效的 ParentFolder。