C# CefSharp应用程序已启动,带有卷影副本

C# CefSharp应用程序已启动,带有卷影副本,c#,.net,winforms,cefsharp,C#,.net,Winforms,Cefsharp,我创建了一个使用ChromiumBrowser的Windows窗体应用程序。该应用程序由以下组件组成: 主要应用 Web浏览器库 启动器应用程序 当我正常启动应用程序时,web浏览器工作正常。如果从启动器启动应用程序,web浏览器将无法工作。它告诉我以下错误: 未知模块中“System.IO.FileNotFoundException”的未处理异常 无法加载文件或程序集“CefSharp,版本=57.0.0.0,区域性=中性,PublicKeyToken=40c4b6fc221f4138”或

我创建了一个使用ChromiumBrowser的Windows窗体应用程序。该应用程序由以下组件组成:

  • 主要应用
  • Web浏览器库
  • 启动器应用程序
当我正常启动应用程序时,web浏览器工作正常。如果从启动器启动应用程序,web浏览器将无法工作。它告诉我以下错误:

未知模块中“System.IO.FileNotFoundException”的未处理异常

无法加载文件或程序集“CefSharp,版本=57.0.0.0,区域性=中性,PublicKeyToken=40c4b6fc221f4138”或相对依赖项

找不到指定的文件

我不仅需要使用启动器进行更新,而且由于应用程序分布在网络上,有时访问服务器上的文件会出现问题

这个问题不仅仅与我的应用程序有关。我在下面发布了一个测试解决方案,我也遇到了同样的问题

项目说明
  • Cefsharp运行时位于C:\Program Files(x86)\CEFRuntime\x64和C:\Program Files(x86)\CEFRuntime\x86中。(我创建了一个安装程序,在这个位置复制运行时文件)。运行时基于NuGet包
  • 所有可执行文件都在AnyCpu中编译(AnyCpu支持)
Cefsharp版本57(Cef redist 3.2987.1601)

运行时内容 x64文件夹

  • cef.pak
  • CefSharp.BrowserSubprocess.Core.dll
  • CefSharp.BrowserSubprocess.Core.pdb
  • CefSharp.BrowserSubprocess.exe
  • CefSharp.BrowserSubprocess.pdb
  • CefSharp.Core.dll
  • CefSharp.Core.pdb
  • CefSharp.Core.xml
  • CefSharp.dll
  • CefSharp.pdb
  • CefSharp.WinForms.dll
  • CefSharp.WinForms.pdb
  • CefSharp.WinForms.XML
  • CefSharp.XML
  • cef_100_percent.pak
  • cef_百分之200.pak
  • cef_extensions.pak
  • chrome_elf.dll
  • d3dcompiler_47.dll
  • devtools_resources.pak
  • icudtl.dat
  • libcef.dll
  • libEGL.dll
  • libGLESv2.dll
  • 土生土长的
  • 快照\u blob.bin
  • widevinecdmadapter.dll
  • locales文件夹(带all.paks)
x86文件夹

  • cef.pak
  • CefSharp.BrowserSubprocess.Core.dll
  • CefSharp.BrowserSubprocess.Core.pdb
  • CefSharp.BrowserSubprocess.exe
  • CefSharp.BrowserSubprocess.pdb
  • CefSharp.Core.dll
  • CefSharp.Core.pdb
  • CefSharp.Core.xml
  • CefSharp.dll
  • CefSharp.pdb
  • CefSharp.WinForms.dll
  • CefSharp.WinForms.pdb
  • CefSharp.WinForms.XML
  • CefSharp.XML
  • cef_100_percent.pak
  • cef_百分之200.pak
  • cef_extensions.pak
  • chrome_elf.dll
  • d3dcompiler_47.dll
  • devtools_resources.pak
  • icudtl.dat
  • libcef.dll
  • libEGL.dll
  • libGLESv2.dll
  • 土生土长的
  • 快照\u blob.bin
  • widevinecdmadapter.dll
  • locales文件夹(带all.paks)
我发布的测试解决方案给了我同样的错误

试液 测试解决方案由三个项目组成:

  • 堆垛机溢出问题清除器
  • StackOverflowIssue(参考WebBrowser)
  • WebBrowser(包含WebBrowser的dll库)
代码如下所示:

项目StackOverflowIssueLancher Program.cs

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace StackOverflowIssueLauncher {

    /// <summary>
    /// Launcher program
    /// </summary>
    internal static class Program {

        /// <summary>
        /// Launcher body
        /// </summary>
        [STAThread, LoaderOptimization(LoaderOptimization.MultiDomainHost)]
        private static void Main() {

            //Initialize path of application
            string startupPath = Environment.CurrentDirectory;
            string cachePath = Path.Combine(Path.GetTempPath(), "Program-" + Guid.NewGuid());
            string assemblyPath = CanonicalizePathCombine(startupPath, @"..\..\..\StackOverflowIssue\bin\Debug\");
            string executablePath = Path.Combine(assemblyPath, "StackOverflowIssue.exe");
            string configFile = executablePath + ".config";

            //Start App Domain
            try {
                var setup = new AppDomainSetup() {
                    ApplicationName = "StackOverflowIssue",
                    ShadowCopyFiles = "true",
                    ShadowCopyDirectories = assemblyPath,
                    CachePath = cachePath,
                    ConfigurationFile = configFile
                };

                var domain = AppDomain.CreateDomain("StackOverflowIssue", AppDomain.CurrentDomain.Evidence, setup);
                domain.ExecuteAssembly(executablePath);
                AppDomain.Unload(domain);
            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            //Empty cache path
            try {
                Directory.Delete(cachePath, true);
            }
            catch (Exception) {
                //DO NOTHING
            }
        }

        private static string CanonicalizePathCombine(string sourcePath, string destPath) {
            string resultPath = Path.Combine(sourcePath, destPath);
            var sb = new StringBuilder(Math.Max(260, 2 * resultPath.Length));
            PathCanonicalize(sb, resultPath);
            return sb.ToString();
        }

        [DllImport("shlwapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern bool PathCanonicalize([Out] StringBuilder sb, string src);
    }
}
using System;
using System.Diagnostics;
using System.Windows.Forms;
using WebBrowser;

namespace StackOverflowIssue {

    /// <summary>
    /// Main application program
    /// </summary>
    internal static class Program {

        /// <summary>
        /// Main application program.
        /// </summary>
        [STAThread] private static void Main() {
            WebBrowserInitializer.Initialize();
            Debug.Print("Application started");
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
    }
}
使用系统;
使用System.IO;
使用System.Runtime.InteropServices;
使用系统文本;
使用System.Windows.Forms;
命名空间StackOverflowIssueLancher{
/// 
///发射程序
/// 
内部静态类程序{
/// 
///发射体
/// 
[STAThread,LoaderOptimization(LoaderOptimization.MultiDomainHost)]
私有静态void Main(){
//初始化应用程序的路径
字符串startupPath=Environment.CurrentDirectory;
字符串cachePath=Path.Combine(Path.GetTempPath(),“Program-”+Guid.NewGuid());
string assemblyPath=CanonicalizePathCombine(startupPath,@.\..\..\StackOverflowIssue\bin\Debug\”;
string executablePath=Path.Combine(assemblyPath,“StackOverflowIssue.exe”);
字符串configFile=executablePath+“.config”;
//启动应用程序域
试一试{
var setup=new-AppDomainSetup(){
ApplicationName=“StackOverflowIssue”,
ShadowCopyFiles=“true”,
ShadowCopyDirectory=assemblyPath,
CachePath=CachePath,
ConfigurationFile=configFile
};
var domain=AppDomain.CreateDomain(“StackOverflowIssue”,AppDomain.CurrentDomain.Evidence,setup);
domain.ExecuteAssembly(可执行路径);
卸载(域);
}
捕获(例外情况除外){
MessageBox.Show(例如Message,“Warning”,MessageBoxButtons.OK,MessageBoxIcon.Error);
}
//空缓存路径
试一试{
Delete(cachePath,true);
}
捕获(例外){
//无所事事
}
}
私有静态字符串CanonicalizePathCombine(字符串源路径、字符串目标路径){
字符串resultPath=Path.Combine(sourcePath,destPath);
var sb=新的StringBuilder(数学最大值(260,2*resultPath.Length));
路径规范化(sb,结果路径);
使某人返回字符串();
}
[DllImport(“shlwapi.dll”,CharSet=CharSet.Auto,SetLastError=true)]
私有静态外部布尔路径规范化([Out]StringBuilder sb,string src);
}
}

项目堆栈溢出问题 WebControlForm.cs

using System.Windows.Forms;
using WebBrowser;

namespace StackOverflowIssue {

    /// <summary>
    /// Form that contains the webbrowser control
    /// </summary>
    public class WebControlForm : Form {

        /// <summary>
        /// Create a new web control form
        /// </summary>
        public WebControlForm() {
            InitializeComponent();
            Controls.Add(new CefControl { Dock = DockStyle.Fill });
        }

        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing) {
            if (disposing && (components != null)) {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent() {
            this.SuspendLayout();
            // 
            // WebControlForm
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(529, 261);
            this.Name = "WebControlForm";
            this.Text = "WebControlForm";
            this.ResumeLayout(false);

        }

        #endregion
    }
}
使用System.Windows.Forms;
使用网络浏览器;
命名空间堆栈溢出问题{
/// 
///包含webbrowser cont的窗体
using System;
using System.Diagnostics;
using System.Windows.Forms;
using WebBrowser;

namespace StackOverflowIssue {

    /// <summary>
    /// Main application program
    /// </summary>
    internal static class Program {

        /// <summary>
        /// Main application program.
        /// </summary>
        [STAThread] private static void Main() {
            WebBrowserInitializer.Initialize();
            Debug.Print("Application started");
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
    }
}
<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="cef.redist.x64" version="3.2987.1601" targetFramework="net452" />
  <package id="cef.redist.x86" version="3.2987.1601" targetFramework="net452" />
  <package id="CefSharp.Common" version="57.0.0" targetFramework="net452" />
  <package id="CefSharp.WinForms" version="57.0.0" targetFramework="net452" />
</packages>
using System.Windows.Forms;
using CefSharp.WinForms;

namespace WebBrowser {

    /// <summary>
    /// WebBrowser control
    /// </summary>
    public class CefControl: UserControl {

        public CefControl() {
            CefInitializer.Initialize();

            InitializeComponent();
            var cr = new ChromiumWebBrowser("https://www.google.com");
            cr.Dock = DockStyle.Fill;
            Controls.Add(cr);
        }

        /// <summary>
        /// Variabile di progettazione necessaria.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Pulire le risorse in uso.
        /// </summary>
        /// <param name="disposing">ha valore true se le risorse gestite devono essere eliminate, false in caso contrario.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Codice generato da Progettazione componenti

        /// <summary>
        /// Metodo necessario per il supporto della finestra di progettazione. Non modificare 
        /// il contenuto del metodo con l'editor di codice.
        /// </summary>
        private void InitializeComponent()
        {
            components = new System.ComponentModel.Container();
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        }

        #endregion
    }
}
using CefSharp;
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Windows.Forms;

namespace WebBrowser {

    /// <summary>
    /// Class that contains the base methods for CEF initializations
    /// </summary>
    public static class CefInitializer {

        /// <summary>
        /// Initialize properties
        /// </summary>
        static CefInitializer() {
            CachePath = Path.Combine(Path.GetTempPath(), "SOIssue", "Cache");
            LogFile = Path.Combine(Path.GetTempPath(), "SOIssue", "Logs");
            UserDataPath = Path.Combine(Path.GetTempPath(), "SOIssue", "Data");

            if (!Directory.Exists(CachePath))
                Directory.CreateDirectory(CachePath);
            if (!Directory.Exists(LogFile))
                Directory.CreateDirectory(LogFile);
            if (!Directory.Exists(UserDataPath))
                Directory.CreateDirectory(UserDataPath);

            //Complete the files combine
            LogFile = Path.Combine(LogFile, "WebBrowser.log");

            AppDomain.CurrentDomain.DomainUnload += (sender, args) => Shutdown();
        }

        /// <summary>
        /// Shutdown all CEF instances
        /// </summary>
        internal static void Shutdown() {
            using (var syncObj = new WindowsFormsSynchronizationContext()) {
                syncObj.Send(o => {
                    if (Cef.IsInitialized)
                        Cef.Shutdown();
                }, new object());
            }
        }

        /// <summary>
        /// Initialize CEF libraries
        /// </summary>
        [MethodImpl(MethodImplOptions.NoInlining)] internal static void Initialize() {
            if (Cef.IsInitialized)
                return;

            //Get proxy properties
            WebProxy proxy = WebRequest.DefaultWebProxy as WebProxy;
            string cefPath = Path.GetDirectoryName(Assembly.GetAssembly(typeof(Cef)).Location);
            Debug.Print($"CEF Library Path: {cefPath}");
            Debug.Assert(cefPath != null, nameof(cefPath) + " != null");

            var settings = new CefSettings() {
                BrowserSubprocessPath = Path.Combine(cefPath, "CefSharp.BrowserSubprocess.exe"),
                LocalesDirPath = Path.Combine(cefPath, "locales"),
                ResourcesDirPath = cefPath,
                Locale = CultureInfo.CurrentCulture.Name,
                CachePath = CachePath,
                LogFile = LogFile,
                UserDataPath = UserDataPath
            };

            if (proxy == null || proxy.Address.AbsoluteUri != string.Empty)
                settings.CefCommandLineArgs.Add("no-proxy-server", string.Empty);

            Cef.Initialize(settings);
        }

        internal static readonly string CachePath;
        internal static readonly string LogFile;
        internal static readonly string UserDataPath;
    }
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;

namespace WebBrowser {

    /// <summary>
    /// Class that contains the assembly resolve functions
    /// </summary>
    public static class WebBrowserInitializer {
        private static readonly object _initializer = new object();
        private static bool _initialized;

        /// <summary>
        /// Check if the WebBrowser is initialized
        /// </summary>
        public static bool IsInitialized {
            get {
                lock (_initializer)
                    return _initialized;
            }
        }

        /// <summary>
        /// Initialize the current assembly
        /// </summary>
        public static void Initialize() {
            lock (_initializer) {
                if (!_initialized) {
                    AppDomain.CurrentDomain.AssemblyResolve += CefSharp_AssemblyResolve;
                    _initialized = true;
                }
            }
        }

        /// <summary>
        /// Try to resolve the assembly
        /// </summary>
        /// <param name="sender">Object that has raised the event</param>
        /// <param name="args">Event raised</param>
        /// <returns>Assembly loaded</returns>
        private static Assembly CefSharp_AssemblyResolve(object sender, ResolveEventArgs args) {
            Debug.Print($"Library: {args.Name}");

            if (!args.Name.StartsWith("CefSharp", StringComparison.OrdinalIgnoreCase))
                return null;

            string assemblyName = args.Name.Split(new[] {','}, 2)[0] + ".dll";

            foreach (var path in GetAssemblyPaths()) {
                string checkPath = Path.Combine(path, assemblyName);

                if (File.Exists(checkPath)) {
                    Debug.Print($"Relative path FOUND for {args.Name} in {checkPath}");
                    return Assembly.UnsafeLoadFrom(checkPath);
                }

                Debug.Write($"Relative path not found for {args.Name} in {checkPath}");
            }

            return null;
        }

        /// <summary>
        /// Get all possible assembly paths
        /// </summary>
        /// <returns>List of possible assembly paths</returns>
        private static IEnumerable<string> GetAssemblyPaths() {
            string pathPrefix = Environment.Is64BitProcess ? "x64" : "x86";

            if (Directory.Exists(@"C:\Program Files (x86)\CEFRuntime\" + pathPrefix))
                yield return @"C:\Program Files (x86)\CEFRuntime\" + pathPrefix;
            
            yield return Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, pathPrefix);
            yield return Path.Combine(Environment.CurrentDirectory, pathPrefix);

            Assembly currentAssembly = Assembly.GetAssembly(typeof(CefInitializer));

            if (!string.IsNullOrEmpty(currentAssembly.Location))
                yield return Path.Combine(currentAssembly.Location, pathPrefix);
        }
    }
}
<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="cef.redist.x64" version="3.2987.1601" targetFramework="net452" />
  <package id="cef.redist.x86" version="3.2987.1601" targetFramework="net452" />
  <package id="CefSharp.Common" version="57.0.0" targetFramework="net452" />
  <package id="CefSharp.WinForms" version="57.0.0" targetFramework="net452" />
</packages>
public static IChildProcessHandle CreateChildProcessHandle() {
    string assemblyPath = _sourcePath ?? Path.GetDirectoryName(Assembly.GetAssembly(typeof(WebBrowserInitializer)).Location);
    Debug.Assert(assemblyPath != null, "assemblyPath != null");
    var al = new ChildProcessFactory() { ClientExecutablePath = _sourcePath };
    return al.Create(Path.Combine(assemblyPath, "MainApplication.WebBrowser.dll"), false, Environment.Is64BitProcess);
}
//Generates client id and server id
string appId = Guid.NewGuid().ToString("N");
string controlId = Guid.NewGuid().ToString("N");

_service = AppServer.Start(appId, controlId);
_service.FormCompleted += Service_FormCompleted;
_locator = new FormServiceLocator(appId, controlId);
_element = _handle.CreateElement(_locator);
_service.StartRemoteClient();
_service.ShowDialog((long)Handle);
private void Service_FormCompleted(object sender, AppServerEventArgs e) {

    //Check if invoke is required
    if (InvokeRequired) {
        Invoke(new Action<object, AppServerEventArgs>(Service_FormCompleted), sender, e);
        return;
    }

    _element = null;

    MessageBox.Show(this, $"Result: {e.Result} - Data: {e.AdditionalData}");
}
var domain = AppDomain.CreateDomain("CefSharp-Remoting", 
AppDomain.CurrentDomain.Evidence, setup);
domain.ExecuteAssembly(executablePath, new[] { $"\"/path:{assemblyPath}\"" });