Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Some or all identity references could not be translated c#

Tags:

c#

I am trying to give the permission to access the folder to the user, but when I am trying to run the program, the error says: Some or all identity references could not be translated.

Here is the code that I am using:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Security;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Management;
using System.Management.Instrumentation;

namespace FolderLock
{
    public partial class Lock : Form
    {
        public Lock()
        {
            InitializeComponent();

            SetAccess();
        }

        private void Lock_Load(object sender, EventArgs e)
        {

        }

        public void SetAccess()
        {
            DirectoryInfo myDirectoryInfo = new DirectoryInfo("C:/Users/Trov/Desktop/Test");

            DirectorySecurity myDirectorySecurity = myDirectoryInfo.GetAccessControl();

            string User = System.Environment.UserDomainName + "\\" + "92111092";

            myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(User, FileSystemRights.Read, AccessControlType.Deny));

            myDirectoryInfo.SetAccessControl(myDirectorySecurity);
        }

    }
}
like image 212
Kaoru Avatar asked Nov 12 '14 17:11

Kaoru


1 Answers

I have found a way, instead of trying to allow or deny the access to the folder by specific users, I just create a well known authenticated users to deny or allow it for access to the folder.

Here is the code:

public void SetAccess()
        {
            DirectoryInfo myDirectoryInfo = new DirectoryInfo(@"C:/Users/Trov/Desktop/Test");

            var sid = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null); 

            DirectorySecurity myDirectorySecurity = myDirectoryInfo.GetAccessControl();

            myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(sid, FileSystemRights.Read, AccessControlType.Deny));

            myDirectoryInfo.SetAccessControl(myDirectorySecurity);

            this.Hide();

            this.Close();
        }

Thank you

like image 88
Kaoru Avatar answered Sep 21 '22 10:09

Kaoru