我遇到了连接“写入”管道到正在运行的服务时,和其他人一样的问题:UnauthorizedAccessException。我尝试了各种解决方案,但没有一种可以成功连接。
情景是有一个低完整性的C#/WPF应用程序在系统托盘中运行,使用命名管道从Windows服务接收通知,并且可以告诉服务取消某些操作或等待更多数据(因此需要一个写入管道到服务)。从服务的管道读取正常,我使用了两个管道对象(一个从服务到客户端,另一个从客户端到服务)。
服务运行在域用户帐户下,但管道无论以什么身份运行都无法连接,包括本地系统。
服务器管道是这样创建的:
PipeSecurity ps = new PipeSecurity();
// Production service runs under current user credentials.
ps.AddAccessRule(new PipeAccessRule(WindowsIdentity.GetCurrent().User, PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance, AccessControlType.Allow));
// Test service runs under local system credentials.
ps.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance, AccessControlType.Allow));
// Add world just for the hell of it, still won't work.
ps.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), PipeAccessRights.FullControl, AccessControlType.Allow));
this.readPipe = new NamedPipeServerStream(clientPipeName, PipeDirection.In);
this.writePipe = new NamedPipeServerStream(serverPipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.None, 1024, 1024, ps);
客户端管道的创建方式如下:
this.readPipe = new NamedPipeClientStream(".", serverPipeName, PipeDirection.In);
this.writePipe = new NamedPipeClientStream(".", clientPipeName, PipeDirection.Out);
// This doesn't make a difference.
//this.writePipe = new NamedPipeClientStream(".", clientPipeName, PipeAccessRights.FullControl, PipeOptions.None, TokenImpersonationLevel.None, HandleInheritability.None);