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

C#程序与Unity《森林》模组间匿名管道访问权限异常解决

解决匿名管道权限拒绝问题的方案
  • 显式配置管道权限与方向
    游戏模组作为管道服务器时,创建AnonymousPipeServerStream要明确指定权限和句柄可继承性,避免Mono环境下默认权限不足:

    var pipeServer = new AnonymousPipeServerStream(
        PipeDirection.Out, 
        HandleInheritability.Inheritable, 
        PipeAccessRights.ReadWrite);
    

    确保服务器方向为Out(向客户端发数据),客户端对应使用PipeDirection.In读取,权限覆盖读写操作。

  • 修正进程启动的句柄传递逻辑
    启动客户端进程时必须关闭ShellExecute,保证句柄能被正确继承,同时释放服务器端的客户端句柄副本:

    string clientHandle = pipeServer.GetClientHandleAsString();
    ProcessStartInfo startInfo = new ProcessStartInfo("PipeClient.exe", clientHandle);
    startInfo.UseShellExecute = false; // 关键:禁用ShellExecute才能继承句柄
    Process.Start(startInfo);
    pipeServer.DisposeLocalCopyOfClientHandle(); // 释放冗余句柄避免权限冲突
    
  • 统一进程运行权限
    若游戏以管理员权限运行,客户端也需以相同权限启动(可在ProcessStartInfo中设置Verb = "runas");同时避免将客户端放在Program Files这类受系统权限管控的目录,移至游戏模组目录或文档目录。

  • 调整Mono环境下的代码执行时机
    将管道服务器逻辑移至后台线程执行,避免Mono主线程的上下文限制:

    void Start()
    {
        Thread pipeThread = new Thread(InitPipeServer);
        pipeThread.IsBackground = true;
        pipeThread.Start();
    }
    
    private void InitPipeServer()
    {
        using (var pipeServer = new AnonymousPipeServerStream(...))
        using (var sw = new StreamWriter(pipeServer))
        {
            sw.AutoFlush = true;
            // 数据发送逻辑
        }
    }
    

    始终用using语句包裹管道流和读写器,确保资源正确释放。

  • 校验客户端初始化代码
    客户端接收句柄后,需用对应方向创建管道流,不要额外修改权限:

    string pipeHandle = args[0];
    using (var pipeClient = new AnonymousPipeClientStream(PipeDirection.In, pipeHandle))
    using (var sr = new StreamReader(pipeClient))
    {
        string temp;
        while ((temp = sr.ReadLine()) != null)
        {
            // 数据处理逻辑
        }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 16:35:01