Программное добавление разрешений безопасности для файлов в C # - PullRequest
7 голосов
/ 24 июня 2009

В приложении asp.net у меня есть задача, которая передает некоторые xml-файлы в локальную папку на моем компьютере. Затем я хочу прочитать эти файлы, но когда они копируются в мою локальную папку, на них не настраивается учетная запись пользователя сетевой службы. Итак, мой вопрос заключается в том, как в .Net C # программно добавить учетную запись «Сетевая служба» с полным контролем к моим XML-файлам.

Ответы [ 4 ]

4 голосов
/ 05 мая 2011

См. Класс FileSecurity в MSDN

В следующем примере кода класс FileSecurity используется для добавления, а затем удаления записи списка управления доступом (ACL) из файла. Вы должны предоставить действительную учетную запись пользователя или группы для запуска этого примера.

using System;
using System.IO;
using System.Security.AccessControl;

namespace FileSystemExample
{
    class FileExample
    {
        public static void Main()
        {
            try
            {
                string fileName = "test.xml";

                Console.WriteLine("Adding access control entry for "
                    + fileName);

                // Add the access control entry to the file.
                AddFileSecurity(fileName, @"DomainName\AccountName",
                    FileSystemRights.FullControl, AccessControlType.Allow);

                Console.WriteLine("Removing access control entry from "
                    + fileName);

                // Remove the access control entry from the file.
                RemoveFileSecurity(fileName, @"DomainName\AccountName",
                    FileSystemRights.FullControl, AccessControlType.Allow);

                Console.WriteLine("Done.");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }

        // Adds an ACL entry on the specified file for the specified account.
        public static void AddFileSecurity(string fileName, string account,
            FileSystemRights rights, AccessControlType controlType)
        {


            // Get a FileSecurity object that represents the
            // current security settings.
            FileSecurity fSecurity = File.GetAccessControl(fileName);

            // Add the FileSystemAccessRule to the security settings.
            fSecurity.AddAccessRule(new FileSystemAccessRule(account,
                rights, controlType));

            // Set the new access settings.
            File.SetAccessControl(fileName, fSecurity);

        }

        // Removes an ACL entry on the specified file for the specified account.
        public static void RemoveFileSecurity(string fileName, string account,
            FileSystemRights rights, AccessControlType controlType)
        {

            // Get a FileSecurity object that represents the
            // current security settings.
            FileSecurity fSecurity = File.GetAccessControl(fileName);

            // Remove the FileSystemAccessRule from the security settings.
            fSecurity.RemoveAccessRule(new FileSystemAccessRule(account,
                rights, controlType));

            // Set the new access settings.
            File.SetAccessControl(fileName, fSecurity);

        }
    }
}
2 голосов
/ 24 июня 2009

Следующая статья (озаглавленная «Установка разрешений NTFS с помощью C #») поможет вам:)

1 голос
/ 26 июня 2009

попробуйте этот код, если помощь

    public static bool CheckReadWriteAccces(string filePath, System.Security.AccessControl.FileSystemRights fileSystemRights)
    {
        FileInfo fileInfo = new FileInfo(filePath);

        string str = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToUpper();
        foreach (System.Security.AccessControl.FileSystemAccessRule rule in fileInfo.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
        {
            if (str == rule.IdentityReference.Value.ToUpper())
                return ((rule.AccessControlType == System.Security.AccessControl.AccessControlType.Allow) && (fileSystemRights == (rule.FileSystemRights & fileSystemRights)));
        }

        return false;
    }


    /// <summary>
    /// Make a file writteble
    /// </summary>
    /// <param name="path">File name to change</param>
    public static void MakeWritable(string path)
    {
        if (!File.Exists(path))
            return;
        File.SetAttributes(path, File.GetAttributes(path) & ~FileAttributes.ReadOnly);
    }
0 голосов
/ 18 февраля 2011
...