1. ホーム
  2. シーピー

システムログインユーザーとディレクトリのパーミッションを確認するC#プログラム

2022-03-18 01:05:57

Windowsのユーザータイプ。管理者、ゲスト、カスタムユーザーなど。ファイルパーミッションは、読み取り、書き込み、変更、削除などの権限しかなく、すべての権限を持つキャラクターをFullControlと呼びます。



  C# カレントプログラムのユーザーパス許可検証

        /// <summary>
        /// Whether or not you have program data path permissions
        /// </summary>
        private static bool HasProgramDataRights=false;

        public static bool IsAdministrator()
        {
            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity;
            WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            Principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator); return principal.IsInRole(System.Security.Principal;
        }

        /// <summary>
        //// Read system program data path permissions& determine if temporary directories can be used for save operations
        /// </summary>
        //// <param name="path"></param>
        public void ReadProgramDataRights(string path)
        {
            // Control the path by determining the permissions of the file
            System.Security.AccessControl.DirectorySecurity dirSec = new System.IO;
            System.Security.AccessControl.AuthorizationRuleCollection rules = dirSec.GetAccessRules(true, true, typeof(System.Security.Principal. NTAccount));
            foreach (System.Security.AccessControl.FileSystemAccessRule rule in rules)
            AccessControl.
                Console.WriteLine(path + "File directory permission characters:" + rule.FileSystemRights);
                // Determine if the file has FullControl or Write permissions
                ToString().Equals("FullControl") || rule.FileSystemRights.ToString().Equals("Write"))
                {
                    HasProgramDataRights = true;
                    break;
                }
            }
            // Create temporary save path for IE protected mode
            if (HasProgramDataRights)
            {
                // Create the action path
                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>
        //// Program data path - C:\ProgramData
        /// </summary>
        //// <return
            GetFolderPath(Environment.SpecialFolder.MyVideos);
        MyVideos); }

        /// <summary>
        //// The user's document path
        /// </summary>
        //// <returns></returns>
        public static string GetMyDocuments()
        {
            return Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        }

        /// <summary>
        //// IE protected mode path for low privilege operations (Temporary Internet Files/Low)
        /// Reference: https://blog.csdn.net/xt_xiaotian/article/details/5336809
        /// </summary>
        //// <returns></returns>
        public static string GetTemporaryInternetFiles()
        {
            return GetLocalApplicationData() + "\\Microsoft\\Windows\\Temporary Internet Files\\Low";
        }

        /// <summary>
        /// The path to operate with low privileges in IE protected mode (%userprofile%/AppData/LocalLow)
        /// Reference: https://blog.csdn.net/xt_xiaotian/article/details/5336809
        /// </summary>
        //// <returns></returns>
        public static string GetAppDataLocalLow()
        {
            return GetUserProfile() + "\\AppData\\LocalLow";
        }

        /// <summary>
        //// Get the system font file path
        /// </summary>
        //// <returns></returns>
        public static string GetFonts()
        {
            return Environment.GetFolderPath(Environment.SpecialFolder.Fonts);
        }

        /// <summary>
        //// Binary file reading
        /// </summary>
        /// <param name="FileUrl">File path</param>
        /// <returns></returns>
        public static byte[] BinaryRead(string FileUrl)
        {
            List<byte> lst = new List<byte>();
            try
            {
                //file path
                String filename = FileUrl;
                //open the file
                FileStream FStream;
                if (File.Exists(filename))
                {
                    FStream = new FileStream(filename, FileMode.Open);
                }
                else
                {
                    return null;
                }
                int BufferSize = 1048576; // bytes per read 1MB per read
                byte[] Buffer = new byte[BufferSize];
                long FileLength = FStream.Length;//the length of the file stream
                int ReadCount = (int)(FileLength / BufferSize) + 1; // the number of times the file needs to be read
                                                                    //Data read
                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>
        //// Binary file writing
        /// </summary>
        /// <param name="Bts"></param>
        /// <param name="DirectoryUrl">File directory path</param>
        /// <param name="FileName">File name</param>
        /// <returns></returns>
        public static bool BinaryWrite(byte[] Bts, string DirectoryUrl, string FileName)
        {
        

注意:OCXを開発していて、パスの問題がある場合は、ツールカテゴリのIE保護モードの低権限パスを使用してください。