简体   繁体   English

Windows 工作器服务文件夹权限 (C#)

[英]Windows Worker Service Folder Permissions (C#)

Quick question if anyone happens to know.快速提问是否有人碰巧知道。 I'm working on a Worker app in dotnet6 that is intended to be made into a service and I need to store a json file somewhere.我正在开发 dotnet6 中的 Worker 应用程序,该应用程序旨在成为服务,我需要在某处存储 json 文件。 Doing some research it seems like CommonApplicationData(ex: "C:/ProgramData") is the place to go.做一些研究,似乎 CommonApplicationData(ex: "C:/ProgramData") 是 go 的地方。 My question is, I can't seem to write a file to that folder.我的问题是,我似乎无法将文件写入该文件夹。 I am able to create a directory just fine.我能够创建一个目录就好了。 But my access is denied to creating an actual file.但是我的访问权限被拒绝创建实际文件。

This service will be used on servers in the field right now and cannot answer UAC prompts.该服务目前将在现场服务器上使用,无法回答 UAC 提示。 I'm unsure what else to do.我不确定还能做什么。 I can have the file created manually and access, edit it.我可以手动创建文件并访问、编辑它。 That seems to work fine.这似乎工作正常。 But I'd like to have a logs files dynamically created and more.但我想动态创建一个日志文件等等。

Heres the code("its pretty basic")这是代码(“它非常基本”)

    var dirPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "MyServerService");
    var path = dirPath + "\\service.json";

    var doesDirExist = Directory.Exists(dirPath);
    var doesFileExist = File.Exists(path);
    if (!doesDirExist || !doesFileExist)
    {
        Directory.CreateDirectory(dirPath); //<- directory is created just fine
        using var file = File.Create(dirPath); // <- fails here (access is denied)
        //do stuff
    }

This bit of code worked for me.这段代码对我有用。 It was indeed a permission issue with the directory being created.这确实是正在创建的目录的权限问题。

  public static bool CreateDirWithAccess(string fullPath, bool readOnly)
{
    var dInfo = Directory.CreateDirectory(fullPath);
    DirectorySecurity dSecurity = dInfo.GetAccessControl();
    dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), readOnly ? FileSystemRights.Read : FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
    dInfo.SetAccessControl(dSecurity);
    return true;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM