蓝色天空网mbsky.com · 知识 · 实践 · 创造ASP · 本地阅读预览
教程 / 后端开发 / ASP

ASP File

核对 Scripting.File 对象的获取方式、GetFile + DateCreated 示例、12 项文件元数据属性及 4 项复制移动删除与流打开方法。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

File 对象的定位与元数据查询场景

`File` 对象封装服务器上单个文件的属性与操作方法,常见检查任务包括查询文件最后修改时间(`DateLastModified`)、最后访问时间(`DateLastAccessed`)以及文件位掩码属性(`Attributes`)。

通过 GetFile 实例化 File 对象与常用操作

获取 `File` 对象需先创建 `FileSystemObject`,再调用 `fs.GetFile("c:\test.txt")` 或遍历 `Folder.Files` 集合;拿到实例 `f` 后即可读取 `f.DateCreated` 等信息,并在结束时将 `f` 与 `fs` 置为 `Nothing`。本地 CPython 3.12.14 离线验证脚本在临时目录中实测了真实文件的时间戳/大小/类型/父目录查询、`Attributes` 读写与 8.3 短文件名推算、`Copy`/`Move`/`Name` 重命名/`Delete` 以及 `OpenAsTextStream` 追加读取。

File 对象属性参考

属性作用说明
Attributes读取或设置文件属性位掩码(如只读 1、隐藏 2、系统 4、存档 32 等)。
DateCreated返回文件的创建日期与时间。
DateLastAccessed返回文件最后一次被访问的日期与时间。
DateLastModified返回文件最后一次被修改的日期与时间。
Drive返回文件所在磁盘驱动器的盘符标识。
Name读取或设置文件名(赋值新名称即可在同目录下重命名文件)。
ParentFolder返回包含该文件的父级 Folder 对象。
Path返回文件的完整路径。
ShortName返回遵循 DOS 8.3 命名约定的短文件名。
ShortPath返回遵循 8.3 命名约定的短路径。
Size返回文件的字节大小。
Type返回基于扩展名注册表映射的文件类型描述(如 Text Document)。

File 对象方法参考

方法作用说明
Copy将当前文件复制到目标路径(支持控制是否覆盖已有目标)。
Delete删除当前文件(可传 force=True 强制删除只读文件)。
Move将当前文件移动到指定目标位置。
OpenAsTextStream以指定读写模式打开当前文件并返回 TextStream 对象。

运行 File 元数据时间戳、属性位掩码、复制移动重命名与流打开离线验证

python · 阅读源码
"""Offline Classic ASP File object verification lab (IIS ASP absent)."""
from datetime import datetime, timezone
import json
from pathlib import Path
import shutil
import tempfile


def derive_short_name(name: str) -> str:
    stem, dot, ext = name.partition(".")
    clean_stem = "".join(ch for ch in stem.upper() if ch.isalnum())
    clean_ext = "".join(ch for ch in ext.upper() if ch.isalnum())[:3]
    short_stem = clean_stem if len(clean_stem) <= 8 else clean_stem[:6] + "~1"
    return f"{short_stem}.{clean_ext}" if dot and clean_ext else short_stem


class MockFile:
    """Offline model of Scripting.File backed by a real temporary file."""

    def __init__(self, path: Path, attributes: int = 32) -> None:
        self._path = path
        self._attributes = attributes

    @property
    def Attributes(self) -> int:
        return self._attributes

    @Attributes.setter
    def Attributes(self, value: int) -> None:
        self._attributes = value

    @property
    def DateCreated(self) -> str:
        st = self._path.stat()
        return datetime.fromtimestamp(st.st_ctime, tz=timezone.utc).strftime("%Y-%m-%d %H:%M:%S")

    @property
    def DateLastAccessed(self) -> str:
        st = self._path.stat()
        return datetime.fromtimestamp(st.st_atime, tz=timezone.utc).strftime("%Y-%m-%d %H:%M:%S")

    @property
    def DateLastModified(self) -> str:
        st = self._path.stat()
        return datetime.fromtimestamp(st.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 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_name(self._path.name)

    @property
    def ShortPath(self) -> str:
        return str(self._path.parent / self.ShortName)

    @property
    def Size(self) -> int:
        return self._path.stat().st_size

    @property
    def Type(self) -> str:
        ext = self._path.suffix.lower()
        return {".txt": "Text Document", ".asp": "Active Server Document"}.get(ext, "File")

    def Copy(self, destination: Path) -> "MockFile":
        shutil.copy2(self._path, destination)
        return MockFile(destination, self._attributes)

    def Move(self, destination: Path) -> None:
        shutil.move(str(self._path), str(destination))
        self._path = destination

    def Delete(self) -> None:
        self._path.unlink()

    def OpenAsTextStream(self, iomode: int = 1):
        mode = {1: "r", 2: "w", 8: "a"}[iomode]
        return self._path.open(mode, encoding="utf-8")


def main() -> None:
    cases = []

    with tempfile.TemporaryDirectory(prefix="asp_file_") as tmp:
        root = Path(tmp)
        p = root / "test.txt"
        p.write_bytes(b"Hello ASP File!")
        f = MockFile(p)

        # Case 1: Metadata & timestamps (DateCreated, DateLastAccessed, DateLastModified, Size, Type, Drive, ParentFolder)
        expected1 = {
            "name": "test.txt",
            "size": 15,
            "type": "Text Document",
            "has_timestamps": True,
            "parent_matches": True,
            "drive_has_colon": True,
        }
        actual1 = {
            "name": f.Name,
            "size": f.Size,
            "type": f.Type,
            "has_timestamps": all(len(ts) == 19 for ts in (f.DateCreated, f.DateLastAccessed, f.DateLastModified)),
            "parent_matches": f.ParentFolder == str(root),
            "drive_has_colon": f.Drive.endswith(":"),
        }
        cases.append({
            "name": "file_metadata_and_timestamps",
            "summary": "Verify File DateCreated/Accessed/Modified, Size, Type, Drive, Path, and ParentFolder.",
            "expected": expected1,
            "actual": actual1,
            "passed": actual1 == expected1,
        })

        # Case 2: Attributes bitmask & 8.3 ShortName / ShortPath
        long_p = root / "LongDocumentName.txt"
        long_p.write_text("8.3 test", encoding="utf-8")
        lf = MockFile(long_p, attributes=32)
        lf.Attributes = lf.Attributes | 1  # Archive + ReadOnly = 33
        expected2 = {
            "attributes": 33,
            "short_name": "LONGDO~1.TXT",
            "short_path_ends_short": True,
        }
        actual2 = {
            "attributes": lf.Attributes,
            "short_name": lf.ShortName,
            "short_path_ends_short": lf.ShortPath.endswith("LONGDO~1.TXT"),
        }
        cases.append({
            "name": "file_attributes_and_short_names",
            "summary": "Verify File Attributes bitmask read/write and 8.3 ShortName/ShortPath convention.",
            "expected": expected2,
            "actual": actual2,
            "passed": actual2 == expected2,
        })

        # Case 3: Copy, Move, Name rename, Delete
        copy_dst = root / "copy.txt"
        copied = f.Copy(copy_dst)
        copied.Name = "renamed.txt"
        moved_dst = root / "sub" / "final.txt"
        moved_dst.parent.mkdir()
        copied.Move(moved_dst)
        moved_exists = moved_dst.is_file()
        copied.Delete()
        after_delete = moved_dst.exists()

        expected3 = {
            "moved_exists": True,
            "after_delete": False,
            "original_intact": True,
        }
        actual3 = {
            "moved_exists": moved_exists,
            "after_delete": after_delete,
            "original_intact": p.is_file(),
        }
        cases.append({
            "name": "file_copy_move_rename_delete",
            "summary": "Verify File.Copy, File.Name rename, File.Move, and File.Delete operations.",
            "expected": expected3,
            "actual": actual3,
            "passed": actual3 == expected3,
        })

        # Case 4: OpenAsTextStream (append + read)
        with f.OpenAsTextStream(8) as fh:
            fh.write("\nAppended")
        with f.OpenAsTextStream(1) as fh:
            lines = fh.read().splitlines()
        expected4 = ["Hello ASP File!", "Appended"]
        cases.append({
            "name": "file_open_as_textstream",
            "summary": "Verify File.OpenAsTextStream appends and reads back updated content.",
            "expected": expected4,
            "actual": lines,
            "passed": lines == 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()
预期结果 · 待实际运行核验
  • 验证真实临时文件的 DateCreated/Accessed/Modified/Size/Type、Attributes 读写与 8.3 短名、Copy/Move/Name/Delete 联动及 OpenAsTextStream 读写。
运行 File 元数据时间戳、属性位掩码、复制移动重命名与流打开离线验证

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:c3ad493a5504c7c25a5e2e0551493d596d241b277cb477412c2ee77aa4a56249

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载ASP File实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:6e2f2c86f6b42a766ecdd4689cf2f520ae70fabda7f8e8824b1865110ee0708f

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

除了 FileSystemObject.GetFile 之外,还有哪种方式可以拿到 File 对象?File.Name 属性为何既是可读又是可写的?

展开参考解答

还可以通过遍历 Folder.Files 集合逐一取得目录内的每个 File 对象;读取 File.Name 返回当前文件名,为 File.Name 赋新字符串则等价于在原地重命名该文件。

规范与官方依据