Last active
August 29, 2015 14:25
-
-
Save Fhernd/09d2ec794c5d81186e9c to your computer and use it in GitHub Desktop.
Demostración de modificación de lista de control de acceso en C#.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// OrtizOL - xCSw - http://ortizol.blogspot.com | |
using System; | |
using System.IO; | |
using System.Security.AccessControl; | |
namespace Receta.CSharp.R0522 | |
{ | |
public class AccesoArchivo | |
{ | |
public static void Main() | |
{ | |
Console.WriteLine(Environment.NewLine); | |
FileStream fs; | |
string nombreArchivo; | |
// Crea un archivo con acceso a todos los usuarios: | |
Console.WriteLine("Presione cualquier tecla para crear un archivo..."); | |
Console.ReadKey(true); | |
// Nombre aleatorio para el archivo: | |
nombreArchivo = Path.GetRandomFileName(); | |
using(fs = new FileStream(nombreArchivo, FileMode.Create)) | |
{ | |
// Escritura del archivo... | |
} | |
Console.WriteLine ("Se ha creado el archivo: {0}\n", nombreArchivo); | |
Console.WriteLine ("Presione cualquier tecla para denegar el acceso al archivo a todos los usuarios..."); | |
Console.ReadKey(true); | |
EstablecerRegla(nombreArchivo, "Todos", FileSystemRights.Read, AccessControlType.Deny); | |
Console.WriteLine ("Se han removido los derechos de acceso de 'Todos'."); | |
Console.WriteLine (); | |
// Intento de acceso al archivo restringido: | |
Console.WriteLine ("Presione cualquier tecla para intentar acceder al archivo {0}...\n", nombreArchivo); | |
Console.ReadKey(true); | |
try | |
{ | |
fs = new FileStream(nombreArchivo, FileMode.Create); | |
} | |
catch(Exception ex) | |
{ | |
Console.WriteLine("Excepción generada: {0}", ex.Message); | |
} | |
finally | |
{ | |
fs.Close(); | |
fs.Dispose(); | |
} | |
Console.WriteLine(Environment.NewLine); | |
} | |
// Método para establecer reglas a un archivo: | |
private static void EstablecerRegla(string rutaArchivo, string cuenta, | |
FileSystemRights permisos, AccessControlType tipoControl) | |
{ | |
// Obtiene el objeto FileSecurity, el cual representa | |
// la configuración de seguridad actual del archivo: | |
FileSecurity seguridadArchivo = File.GetAccessControl(rutaArchivo); | |
// Configura relga de seguridad: | |
seguridadArchivo.ResetAccessRule(new FileSystemAccessRule(cuenta, | |
permisos, tipoControl)); | |
// Establece la regla de seguridad: | |
File.SetAccessControl(rutaArchivo, seguridadArchivo); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment