【问题标题】:System.UnauthorizedAccessException: 'Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))'System.UnauthorizedAccessException: '访问被拒绝。 (来自 HRESULT 的异常:0x80070005 (E_ACCESSDENIED))'
【发布时间】:2026-02-05 08:05:02
【问题描述】:

您好,我正在使用 C# 开发 VPN,这是我的代码

VpnManagementAgent vpnManagementAgent = new VpnManagementAgent();
        VpnManagementAgent mgr = vpnManagementAgent;
        VpnNativeProfile profile = new VpnNativeProfile()
        {
            AlwaysOn = false,
            NativeProtocolType = VpnNativeProtocolType.IpsecIkev2,
            ProfileName = "MyConnection",
            RememberCredentials = true,
            RequireVpnClientAppUI = true,
            RoutingPolicyType = VpnRoutingPolicyType.SplitRouting,
            TunnelAuthenticationMethod = VpnAuthenticationMethod.Certificate,
            UserAuthenticationMethod = VpnAuthenticationMethod.Mschapv2,
        };
        profile.Servers.Add("serveAddress");
        VpnManagementErrorStatus profileStatus = await mgr.AddProfileFromObjectAsync(profile);
        PasswordCredential credentials = new PasswordCredential
        {
            UserName = "username",
            Password = "Abc",
        };
        VpnManagementErrorStatus connectStatus = await mgr.ConnectProfileWithPasswordCredentialAsync(profile, credentials);

我在按钮操作上添加了所有这些代码。现在当我开始 VPN 连接时,这条线抛出异常

VpnManagementErrorStatus profileStatus = await mgr.AddProfileFromObjectAsync(profile);

例外是

 System.UnauthorizedAccessException: 'Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))'

堆栈跟踪:

at Windows.Networking.Vpn.VpnManagementAgent.AddProfileFromObjectAsync(IVpnProfile profile)
at App1.MainPage.<Button_Click>d__2.MoveNext() in C:\Users\HP\source\repos\StarkVPnTesting\App1\MainPage.xaml.cs:line 62

【问题讨论】:

  • 最好也共享堆栈跟踪。
  • 我更新了我的问题并添加了 stackTrace

标签: c# visual-studio vpn


【解决方案1】:

我认为您需要按以下方式添加应用功能“networkingVpnProvider”:

此链接描述了应用功能MSDN App Capability 的意义以及如何应用。最终,您需要将以下内容添加到您的应用程序包清单源文件 (Package.appxmanifest)。

<?xml version="1.0" encoding="utf-8"?>
<Package
    ...
    xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
    IgnorableNamespaces="... rescap">
...
<Capabilities>
    <rescap:Capability Name="networkingVpnProvider"/>
</Capabilities>
</Package>

请注意,根据该方法的文档,这是 Windows 10 的要求:VpnManagementAgent.AddProfileFromObjectAsync(IVpnProfile) Method

【讨论】:

  • 如何查看Console.WriteLine("someText")的日志
  • 您可以在 Visual Studio 的 output 窗口中找到它们。 “Ctrl+Alt+O”打开输出窗口。
  • 感谢我将 console.WriteLine 更改为 System.Diagnostics.Debug.WriteLine 并开始工作
  • 如何获取await关键字的状态我想获取connectStatus
  • 您不会问“额外问题” :) 有新问题吗?发布一个新问题! :)
最近更新 更多