简体   繁体   中英

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. Doing some research it seems like CommonApplicationData(ex: "C:/ProgramData") is the place to 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. 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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