You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Selenium的C# SaveAsFile方法中能否使用相对路径?

解决Selenium C# SaveAsFile使用相对路径的问题

在C#的Selenium中,SaveAsFile方法支持相对路径,但要注意路径基准是当前应用程序的工作目录,且目标目录需提前创建(方法不会自动生成目录)。以下是两种可靠的实现方案:

方式1:直接使用相对路径(需确保目录存在)

如果想把截图存在项目根目录下的screenshots文件夹,直接写相对路径即可,同时要先判断并创建目标目录:

ITakesScreenshot tss = driver as ITakesScreenshot;
Screenshot ss = tss.GetScreenshot();

// 定义相对路径
string relativePath = "screenshots/MyScreenshot.jpg";
// 拼接为完整路径(可选,用于验证路径正确性)
string fullPath = Path.Combine(Directory.GetCurrentDirectory(), relativePath);

// 确保目标目录存在
string directory = Path.GetDirectoryName(fullPath);
if (!Directory.Exists(directory))
{
    Directory.CreateDirectory(directory);
}

ss.SaveAsFile(fullPath, ScreenshotImageFormat.Jpeg);

方式2:基于程序基目录构建相对路径

如果要更稳妥地指向项目相关目录,可以用AppDomain.CurrentDomain.BaseDirectory获取程序运行的基目录(通常是项目的输出目录,如bin/Debug/net6.0),再组合相对路径:

ITakesScreenshot tss = driver as ITakesScreenshot;
Screenshot ss = tss.GetScreenshot();

// 获取程序基目录
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
// 回退到项目根目录(根据你的输出目录结构调整回退层级)
string projectRoot = Directory.GetParent(baseDir).Parent.Parent.FullName;
// 拼接最终截图路径
string screenshotPath = Path.Combine(projectRoot, "screenshots", "MyScreenshot.jpg");

// 确保目标目录存在
string directory = Path.GetDirectoryName(screenshotPath);
if (!Directory.Exists(directory))
{
    Directory.CreateDirectory(directory);
}

ss.SaveAsFile(screenshotPath, ScreenshotImageFormat.Jpeg);

关键注意事项

  • 相对路径的默认基准是当前工作目录,可通过Directory.GetCurrentDirectory()查看当前路径,避免路径混乱。
  • 必须提前创建目标目录,否则SaveAsFile会抛出DirectoryNotFoundException。
  • 单元测试项目的工作目录可能与普通控制台项目不同,优先用AppDomain的方式更可靠。

内容的提问来源于stack exchange,提问作者Mateusz Wąsik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 15:33:25