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

Error CS0712:无法创建静态类'File'实例的问题如何解决?

问题:C# WinForm中使用Selenium添加Chrome扩展时出现CS0712错误

我编写了一段结合Selenium的C# WinForm代码,尝试通过new File("pathtoextentions.crx")为ChromeOptions添加扩展时,触发了Error CS0712错误,提示无法创建静态类'File'的实例。

代码示例

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace test
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            ChromeOptions options = new ChromeOptions();
            options.AddExtensions(new File("pathtoextentions.crx"));

            IWebDriver driver = new ChromeDriver(options);
            //Test Opening Website
            driver.Navigate().GoToUrl("https://google.com");
        }
    }
}

错误提示

英文提示:Error CS0712 Cannot create an instance of the static class 'File'
中文翻译:错误 CS0712 无法创建静态类“File”的实例


问题原因及解决方法

  • 问题根源:你代码里的File是.NET类库中的System.IO.File,这是一个静态类,C#语法规定静态类不能通过new关键字创建实例。
  • 两种修正方案:
    1. 直接传入文件路径字符串(最简单):
      options.AddExtensions("pathtoextentions.crx");
      
    2. 使用FileInfo类(需添加System.IO命名空间引用):
      // 先在代码顶部添加引用:using System.IO;
      options.AddExtensions(new FileInfo("pathtoextentions.crx"));
      
  • 注意事项:确保crx文件的路径正确(推荐使用绝对路径),且文件存在、程序有读取权限。

内容的提问来源于stack exchange,提问作者Gearzo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 15:25:19