Windows服务和命名管道:UnauthorizedAccessException

时间:2013-03-07 11:36:37

标签: c# .net windows-services named-pipes

当我尝试从WPF-Testapp访问NamedPipeServer(作为WindowsService运行)时,我总是会收到UnauthorizedAccessException。

服务器:

 class PipeConnector
    {
        private volatile bool _shouldStop;
        NamedPipeServerStream pipeServer;
        public PipeConnector()
        {
            _shouldStop = false;
            PipeSecurity ps = new PipeSecurity();
            ps.AddAccessRule(new PipeAccessRule(WindowsIdentity.GetCurrent().Name, PipeAccessRights.ReadWrite, AccessControlType.Allow));
            pipeServer = new NamedPipeServerStream("ConnectorPipe", PipeDirection.InOut, 10,
                                    PipeTransmissionMode.Message,
                                    PipeOptions.WriteThrough, 4028, 4028, ps);    
        }

        public void Start()
        {
            pipeServer.WaitForConnection();

            StreamWriter sw = new StreamWriter(pipeServer);

            while (!_shouldStop)
            {
                sw.WriteLine("Here is Server, I'm working");
                sw.Flush();
                Thread.Sleep(5000);
            }
            this.pipeServer.Close();
        }

        public void RequestStop()
        {
            this._shouldStop = true;
            this.pipeServer.Close();
        }
    }

客户端:

public delegate void Notification(string text);
    class PipeConnector
    {

        NamedPipeClientStream pipeClient;
        public Notification notify;
        public PipeConnector()
        {
             pipeClient =
                    new NamedPipeClientStream(".", "ConnectorPipe",
                        PipeDirection.InOut);
        }

        public void Start()
        { 
            pipeClient.Connect();
            StreamReader sr = new StreamReader(pipeClient);

            while (true)
            {
                string text = sr.ReadLine();
                notify(text);
            }

        }
    }

我找到了类似问题的很多解决方案,但没有人为我工作..

我也试过这个:http://support.microsoft.com/kb/126645/en-us

提前致谢!

1 个答案:

答案 0 :(得分:1)

嗯..我搞定了。

解决方案:

而不是WindowsIdentity.GetCurrent().Name我使用了new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null)