c# - Preventing a user from deleting, modifying, ext -
i need make program reads data text file , changes program state according specific data found in text file, program needs privileges read, write , create text file.
i want users or other software prevented deleting, modifying, or copying file. how begin implement this?
you can achieve in 3 ways:
1) application starts filehandle , lock file. of course work if applications runs (for example service) time
2) adjust priviledges in files security tab , set read only. create technical user write access (works best in domains). open file in program technical user while using impersionation (windowsimpersonationcontext). using simple:
using (new impersonation(domain, username, password)) { // whatever want }
a sample class windowsimpersonationcontext (should work charm):
[permissionset(securityaction.demand, name = "fulltrust")] public class impersonation : idisposable { private readonly safetokenhandle _handle; private readonly windowsimpersonationcontext _context; const int logon32_logon_new_credentials = 9; public impersonation(string domain, string username, string password) { var ok = logonuser(username, domain, password, logon32_logon_new_credentials, 0, out this._handle); if (!ok) { var errorcode = marshal.getlastwin32error(); throw new applicationexception(string.format("could not impersonate elevated user. logonuser returned error code {0}.", errorcode)); } this._context = windowsidentity.impersonate(this._handle.dangerousgethandle()); } public void dispose() { this._context.dispose(); this._handle.dispose(); } [dllimport("advapi32.dll", setlasterror = true, charset = charset.unicode)] private static extern bool logonuser(string lpszusername, string lpszdomain, string lpszpassword, int dwlogontype, int dwlogonprovider, out safetokenhandle phtoken); public sealed class safetokenhandle : safehandlezeroorminusoneisinvalid { private safetokenhandle() : base(true) { } [dllimport("kernel32.dll")] [reliabilitycontract(consistency.willnotcorruptstate, cer.success)] [suppressunmanagedcodesecurity] [return: marshalas(unmanagedtype.bool)] private static extern bool closehandle(intptr handle); protected override bool releasehandle() { return closehandle(handle); } } }
another attempt (including using) shown here: open shared file under user , domain?
3) running program different user has access rights - other users have readonly rights (use technical user when registered service or runas /user command)
Comments
Post a Comment