Проблема, с которой я столкнулся, заключается в том, что канал может не буду взаимодействовать с графическим интерфейсом, если графический интерфейс не будет запущен с правами администратора. Если я попытаюсь получить доступ к каналу без прав администратора, я получу ошибку «Доступ к пути запрещен». Я также пытался передать значение PipeSecurity, однако затем получаю сообщение об ошибке: время ожидания операции истекло.
Вот код, который я запускаю с переданной опцией PipeSecurity;
Код: Выделить всё
private async Task ListenForPipeRequests(CancellationToken token)
{
while (!token.IsCancellationRequested) {
PipeSecurity security = CreatePipeSecurity();
using (var server = NamedPipeServerStreamAcl.Create(
"my_unique_pipe_name",
PipeDirection.InOut,
1, // maxNumberOfServerInstances
PipeTransmissionMode.Byte,
PipeOptions.Asynchronous,
1024, // inBufferSize
1024, // outBufferSize
security, // pipeSecurity
HandleInheritability.Inheritable,
PipeAccessRights.FullControl))
{
try
{
await server.WaitForConnectionAsync(token);
using (var reader = new StreamReader(server))
using (var writer = new StreamWriter(server) { AutoFlush = true })
{
string? message;
while ((message = await reader.ReadLineAsync()) != null)
{
// Process the received message
string response2 = HandleRequest(message);
// Optionally send a response
await writer.WriteLineAsync(response2);
}
}
}
catch (OperationCanceledException ex)
{
// Handle cancellation
SaveToLog("Cancelation: " + ex.Message);
}
catch (IOException ioex)
{
// Handle pipe broken or other IO exceptions
SaveToLog("IO Exception: " + ioex.Message);
}
catch (Exception ex)
{
SaveToLog("Exception: " + ex.Message);
}
}
}
}
private PipeSecurity CreatePipeSecurity()
{
var pipeSecurity = new PipeSecurity();
// Grant full control to the current user
var currentUser = WindowsIdentity.GetCurrent().User;
pipeSecurity.AddAccessRule(new PipeAccessRule(
currentUser,
PipeAccessRights.FullControl,
AccessControlType.Allow));
// Grant full control to the Local System account
pipeSecurity.AddAccessRule(new PipeAccessRule(
new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null),
PipeAccessRights.FullControl,
AccessControlType.Allow));
// Grant full control to Administrators
pipeSecurity.AddAccessRule(new PipeAccessRule(
new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null),
PipeAccessRights.FullControl,
AccessControlType.Allow));
// Grant read/write access to everyone
pipeSecurity.AddAccessRule(new PipeAccessRule(
new SecurityIdentifier(WellKnownSidType.WorldSid, null),
PipeAccessRights.ReadWrite,
AccessControlType.Allow));
return pipeSecurity;
}
Код: Выделить всё
using (var server = new NamedPipeServerStream("my_unique_pipe_name", PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
{ ... }
Есть ли у кого-нибудь мысли о том, что может быть причиной моей проблемы? Кажется, это обычная проблема, однако я не могу найти ни одной темы, использующей последнюю версию .NET. AddAccessRules, возможно, сейчас слишком щедры, но это потому, что я не могу понять, в чем дело. Я устанавливаю службу с помощью sc.exe и запускаю графический интерфейс с помощью отладчика Visual Studio, если это имеет значение.
Я очень ценю любой ваш вклад; спасибо!
Подробнее здесь: https://stackoverflow.com/questions/786 ... amed-pipes