亲宝软件园·资讯

展开

C#验证登录用户与目录权限 使用C#程序验证系统登录用户与目录权限

boonya 人气:0

Windows用户类型:Administrator、Guest、自定义用户等;文件的权限不外乎:Read、Write、Modify、Remove等等,其中拥有所有权限的字符叫做FullControl。

C#当前程序用户路径权限验证

/// <summary>
  /// 是否拥有程序数据路径权限
  /// </summary>
  private static bool HasProgramDataRights=false;
 
  public static bool IsAdministrator()
  {
   System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
   System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
   return principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
  }
 
  /// <summary>
  /// 读取系统程序数据路径权限&判断是否可以使用临时目录进行保存操作
  /// </summary>
  /// <param name="path"></param>
  public void ReadProgramDataRights(string path)
  {
   // 通过判定文件的权限来控制路径
   System.Security.AccessControl.DirectorySecurity dirSec = new System.IO.DirectoryInfo(path).GetAccessControl();
   System.Security.AccessControl.AuthorizationRuleCollection rules = dirSec.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));
   foreach (System.Security.AccessControl.FileSystemAccessRule rule in rules)
   {
    Console.WriteLine(path + "文件目录权限字符:" + rule.FileSystemRights);
    // 判定文件是否具有FullControl或Write权限
    if (rule.FileSystemRights.ToString().Equals("FullControl") || rule.FileSystemRights.ToString().Equals("Write"))
    {
     HasProgramDataRights = true;
     break;
    }
   }
   // 为IE保护模式创建临时保存路径
   if (HasProgramDataRights)
   {
    // 创建操作路径
    string recordTemp = FileHelp.GetAppDataLocalLow() + "\\CvNetVideo\\Record\\";
    string screenshotTemp = FileHelp.GetAppDataLocalLow() + "\\CvNetVideo\\Screenshot\\";
    string recordDst = FileHelp.GetCommonApplicationData() + "\\CvNetVideo\\Record\\";
    string screenshotDst = FileHelp.GetCommonApplicationData() + "\\CvNetVideo\\Screenshot\\";
    Directory.CreateDirectory(recordTemp);
    Directory.CreateDirectory(screenshotTemp);
    Directory.CreateDirectory(recordDst);
    Directory.CreateDirectory(screenshotDst);
   }
  }

C#文件操作工具类

public class FileHelp
 {
  public enum GetDirectoryType
  {
   ByAppDomain,
   ByAssembly
  }
  public static string GetCurrentDirectory(GetDirectoryType type = GetDirectoryType.ByAppDomain)
  {
   switch (type)
   {
    case GetDirectoryType.ByAppDomain:
     return AppDomain.CurrentDomain.BaseDirectory;
    case GetDirectoryType.ByAssembly:
 
     return Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
    default:
     return AppDomain.CurrentDomain.BaseDirectory;
   }
  }
  public static string GetCurrentDirectoryByAssembly()
  {
   return GetCurrentDirectory(GetDirectoryType.ByAssembly);
  }
 
  /// <summary>
  ///程序数据路径- C:\ProgramData
  /// </summary>
  /// <returns></returns>
  public static string GetCommonApplicationData()
  {
   return Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
  }
 
  /// <summary>
  /// 用户数据路径
  /// </summary>
  /// <returns></returns>
  public static string GetApplicationData()
  {
   return Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
  }
 
  /// <summary>
  /// 用户数据本地路径
  /// </summary>
  /// <returns></returns>
  public static string GetLocalApplicationData()
  {
   return Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
  }
 
  /// <summary>
  /// 用户路径
  /// </summary>
  /// <returns></returns>
  public static string GetUserProfile()
  {
   return Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
  }
 
  /// <summary>
  /// 用户的图片路径
  /// </summary>
  /// <returns></returns>
  public static string GetMyPictures()
  {
   return Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
  }
 
  /// <summary>
  /// 用户的视频路径
  /// </summary>
  /// <returns></returns>
  public static string GetMyVideos()
  {
   return Environment.GetFolderPath(Environment.SpecialFolder.MyVideos);
  }
 
  /// <summary>
  /// 用户的文档路径
  /// </summary>
  /// <returns></returns>
  public static string GetMyDocuments()
  {
   return Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
  }
 
  /// <summary>
  /// IE保护模式下的低权限操作路径(Temporary Internet Files/Low)
  /// </summary>
  /// <returns></returns>
  public static string GetTemporaryInternetFiles()
  {
   return GetLocalApplicationData()+ "\\Microsoft\\Windows\\Temporary Internet Files\\Low";
  } 
  /// <summary>
  /// IE保护模式下的低权限操作路径(%userprofile%/AppData/LocalLow)
  /// </summary>
  /// <returns></returns>
  public static string GetAppDataLocalLow()
  {
   return GetUserProfile() + "\\AppData\\LocalLow";
  }
 
  /// <summary>
  /// 获取系统字体文件路径
  /// </summary>
  /// <returns></returns>
  public static string GetFonts()
  {
   return Environment.GetFolderPath(Environment.SpecialFolder.Fonts);
  } 
  /// <summary>
  /// 二进制文件读取
  /// </summary>
  /// <param name="FileUrl">文件路径</param>
  /// <returns></returns>
  public static byte[] BinaryRead(string FileUrl)
  {
   List<byte> lst = new List<byte>();
   try
   {
    //文件路径
    String filename = FileUrl;
    //打开文件
    FileStream FStream;
    if (File.Exists(filename))
    {
     FStream = new FileStream(filename, FileMode.Open);
    }
    else
    {
     return null;
    }
    int BufferSize = 1048576; //每次读取的字节数 每次读取1MB
    byte[] Buffer = new byte[BufferSize];
    long FileLength = FStream.Length;//文件流的长度
    int ReadCount = (int)(FileLength / BufferSize) + 1; //需要对文件读取的次数
                 //数据读取
    BinaryReader BWrite = new BinaryReader(FStream);
    //br.BaseStream.Seek(0, SeekOrigin.Begin);
    //while (br.BaseStream.Position < br.BaseStream.Length){}
    for (int a = 0; a < ReadCount; a++)
    {
     Buffer = BWrite.ReadBytes(BufferSize);
     lst.AddRange(Buffer);
    }
    BWrite.Close();
    BWrite.Close();
    return lst.ToArray();
   }
   catch (System.Exception ex)
   {
    Log.WriteLog4Ex("FileHelp.BinaryRead", ex);
    return null;
   }
  } 
  /// <summary>
  /// 二进制文件写入
  /// </summary>
  /// <param name="Bts"></param>
  /// <param name="DirectoryUrl">文件目录路径</param>
  /// <param name="FileName">文件名称</param>
  /// <returns></returns>
  public static bool BinaryWrite(byte[] Bts, string DirectoryUrl, string FileName)
  {
   try
   {
    //文件路径
    string Filepath = DirectoryUrl + "\\" + FileName;
    //目录创建
    if (!Directory.Exists(DirectoryUrl))
     Directory.CreateDirectory(DirectoryUrl);
    //文件创建
    FileStream FStream;
    if (File.Exists(Filepath))
    {
     FStream = new FileStream(Filepath, FileMode.Append);
    }
    else
    {
     FStream = new FileStream(Filepath, FileMode.Create);
    }
    //数据写入
    BinaryWriter BWrite = new BinaryWriter(FStream);
    BWrite.Write(Bts);
    BWrite.Close();
    FStream.Close();
    return true;
   }
   catch (System.Exception ex)
   {
    Log.WriteLog4Ex("FileHelp.BinaryWrite", ex);
    return false;
   }
  } 
  /// <summary>
  /// 二进制文件删除
  /// </summary>
  /// <param name="FileUrl">文件路径</param>
  public static void FileDelete(string FileUrl)
  {
   try
   {
    //文件路径
    String filename = FileUrl;
    //删除文件
    if (File.Exists(filename))
    {
     File.Delete(filename);
    }
   }
   catch (System.Exception ex)
   {
    Log.WriteLog4Ex("FileHelp.FileDelete", ex);
   }
  }
 }

注:如果您是开发OCX遇到路径问题请使用工具类中IE保护模式下的低权限路径。

补充知识:C#修改文件或文件夹的权限,为指定用户、用户组添加完全控制权限

写在前面

在windows系统中,c盘中的目录权限比较高,有时制作安装包的时候,默认的安装路径就是在c盘,但对运行可执行文件,有时候需要为其添加完全控制权限,或者读写权限。这里将当时的解决方案记录一下。

代码实现

在C盘添加一个文件夹,并在文件夹内部,新建一个文本文件,如图所示:

该文件夹下,新建一个文本文件,如图所示:

为文件添加完全控制权限:

/// <summary>
  /// 为文件添加users,everyone用户组的完全控制权限
  /// </summary>
  /// <param name="filePath"></param>
  static void AddSecurityControll2File(string filePath)
  {

   //获取文件信息
   FileInfo fileInfo = new FileInfo(filePath);
   //获得该文件的访问权限
   System.Security.AccessControl.FileSecurity fileSecurity = fileInfo.GetAccessControl();
   //添加ereryone用户组的访问权限规则 完全控制权限
   fileSecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
   //添加Users用户组的访问权限规则 完全控制权限
   fileSecurity.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow));
   //设置访问权限
   fileInfo.SetAccessControl(fileSecurity);
  }

为文件夹添加完全控制权限

/// <summary>
  ///为文件夹添加users,everyone用户组的完全控制权限
  /// </summary>
  /// <param name="dirPath"></param>
  static void AddSecurityControll2Folder(string dirPath)
  {
   //获取文件夹信息
   DirectoryInfo dir = new DirectoryInfo(dirPath);
   //获得该文件夹的所有访问权限
   System.Security.AccessControl.DirectorySecurity dirSecurity = dir.GetAccessControl(AccessControlSections.All);
   //设定文件ACL继承
   InheritanceFlags inherits = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
   //添加ereryone用户组的访问权限规则 完全控制权限
   FileSystemAccessRule everyoneFileSystemAccessRule = new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);
   //添加Users用户组的访问权限规则 完全控制权限
   FileSystemAccessRule usersFileSystemAccessRule = new FileSystemAccessRule("Users", FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);
   bool isModified = false;
   dirSecurity.ModifyAccessRule(AccessControlModification.Add, everyoneFileSystemAccessRule, out isModified);
   dirSecurity.ModifyAccessRule(AccessControlModification.Add, usersFileSystemAccessRule, out isModified);
   //设置访问权限
   dir.SetAccessControl(dirSecurity);
  }

总结

在操作文件的时候,还是比较简单的,不过文件夹就比较复杂了,牵扯到是否要继承的问题。

以上这篇使用C#程序验证系统登录用户与目录权限就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

加载全部内容

相关教程
猜你喜欢
用户评论