Csharp/CSharp Tutorial/File Directory Stream/File Access Rule — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 12:20, 26 мая 2010
Add file access rule
using System;
using System.IO;
using System.Security.AccessControl;
static class MainClass
{
static void Main(string[] args)
{
FileStream stream = null;
string fileName = "c:\\Test.txt";
// Deny "Everyone" access to the file
FileSecurity fSecurity = File.GetAccessControl(fileName);
fSecurity.AddAccessRule(new FileSystemAccessRule("Everyone",FileSystemRights.Read, AccessControlType.Deny));
File.SetAccessControl(fileName, fSecurity);
// Attempt to access file.
try
{
stream = new FileStream(fileName, FileMode.Create);
}
catch (Exception ex)
{
Console.WriteLine("Exception thrown: ");
Console.WriteLine(ex.ToString());
}
finally
{
stream.Close();
stream.Dispose();
}
}
}
Creating a new file with specific access rule
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Security;
using System.Security.AccessControl;
using System.Security.Policy;
using System.Security.Permissions;
using System.Security.Principal;
using System.Text;
public class MainClass
{
public static void Main()
{
string fileName = "c:\\test.txt";
FileSecurity acl = new FileSecurity();
acl.AddAccessRule(new FileSystemAccessRule(WindowsIdentity.GetCurrent().Name,
FileSystemRights.CreateFiles | FileSystemRights.Modify | FileSystemRights.Delete,
AccessControlType.Allow));
using (FileStream file = File.Open(fileName, FileMode.OpenOrCreate))
{
}
}
}
Set File access rule
using System;
using System.IO;
using System.Security.AccessControl;
static class MainClass
{
static void Main(string[] args)
{
FileStream stream = null;
string fileName = "c:\\test.txt";
// Deny "Everyone" access to the file
FileSecurity fSecurity = File.GetAccessControl(fileName);
fSecurity.ResetAccessRule(new FileSystemAccessRule("Everyone",FileSystemRights.Read, AccessControlType.Deny));
File.SetAccessControl(fileName, fSecurity);
// Attempt to access file.
try
{
stream = new FileStream(fileName, FileMode.Create);
}
catch (Exception ex)
{
Console.WriteLine("Exception thrown: ");
Console.WriteLine(ex.ToString());
}
finally
{
stream.Close();
stream.Dispose();
}
}
}