// Methods
 public static bool FileExists(string filePath)
 {
     if (File.Exists(filePath))
     {
         return true;
     }
     FileIOPermission permission = null;
     try
     {
         permission = new FileIOPermission(FileIOPermissionAccess.AllAccess, filePath);
     }
     catch
     {
         return false;
     }
     try
     {
         permission.Demand();
     }
     catch (Exception exception)
     {
         //
     }
     return false;
 }
Example #2
0
        public static bool CopyFile(string newFile, string oldFile)
        {
            var newfile = new FileInfo(newFile);
            var oldfile = new FileInfo(oldFile);
            string errorMsg = "";
            var f2 = new FileIOPermission(FileIOPermissionAccess.AllAccess, oldFile);
            f2.AddPathList(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, newFile);

            try
            {
                f2.Demand();
            }
            catch (SecurityException s)
            {
                Console.WriteLine(s.Message);
            }

               for (int x = 0; x < 100; x++)
               {
                    try
                    {
                       File.Delete(oldfile.FullName);
                       newfile.CopyTo(oldfile.FullName, true);
                       return true;
                    }
                    catch(Exception e)
                    {
                        errorMsg = e.Message + " :   " + e.InnerException;
                        Thread.Sleep(200);
                    }
               }
            Data.Logger(errorMsg);
               return false;
        }
Example #3
0
        public void Capture( OnlineCaptureInfo info )
        {
            try
            {
                // Ensure permission to write to the archive directory.
                FileIOPermission p = new FileIOPermission( FileIOPermissionAccess.Write,
                    new FileInfo( info.ArchiveDir ).FullName );
                p.Demand();

                logger = info.Logger;

                string html = CaptureText( info.AccountName, info.Credentials );

                // Write HTML results to file

                string filename = Path.Combine( info.ArchiveDir, info.BaseName + ".htm" );
                info.CapturedFiles.Add( Path.GetFileName( filename ) );

                File.WriteAllText( filename, html );
            }
            catch( SecurityException ex )
            {
                throw new OnlineReaderException( "Security violation: " + ex.Message, ex );
            }
        }
         public Image ScanImage(ImageFormat outputFormat, string fileName)
         {
              if (outputFormat == null)
                   throw new ArgumentNullException("outputFormat");

              FileIOPermission filePerm = new FileIOPermission(FileIOPermissionAccess.AllAccess, fileName);
              filePerm.Demand();

              ImageFile imageObject = null;

              try
              {
                   if (WiaManager == null)
                        WiaManager = new CommonDialogClass();

                   imageObject =
                        WiaManager.ShowAcquireImage(WiaDeviceType.ScannerDeviceType,
                             WiaImageIntent.GrayscaleIntent, WiaImageBias.MaximizeQuality, 
                             outputFormat.Guid.ToString("B"), false, true, true);

                   imageObject.SaveFile(fileName);
                   return Image.FromFile(fileName);
              }
              catch (COMException ex)
              {
                   string message = "Error scanning image";
                   throw new WiaOperationException(message, ex);
              }
              finally
              {
                   if (imageObject != null)
                        Marshal.ReleaseComObject(imageObject);
              }
         }
        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            base.Initialize(name, config);

            if (string.IsNullOrEmpty(config["dataStorePath"]))
                throw new ProviderException("dataStorePath config attribute is required.");

            this._dataStorePath = config["dataStorePath"];

            if (!VirtualPathUtility.IsAppRelative(this._dataStorePath))
                throw new ArgumentException("dataStorePath must be app-relative");

            string fullyQualifiedPath = VirtualPathUtility.Combine(
                VirtualPathUtility.AppendTrailingSlash(HttpRuntime.AppDomainAppVirtualPath),
                this._dataStorePath);

            this._dataStorePath = HostingEnvironment.MapPath(fullyQualifiedPath);

            config.Remove("dataStorePath");

            // Make sure we have permission to read the XML data source and
            // throw an exception if we don't
            if (!Directory.Exists(this._dataStorePath))
                Directory.CreateDirectory(this._dataStorePath);

            FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.AllAccess, this._dataStorePath);
            permission.Demand();

            if (config.Count > 0)
                throw new ProviderException(string.Format("Unknown config attribute '{0}'", config.GetKey(0)));
        }
Example #6
0
        private static string _strRootFolder;  //定义操作的根目录

        /// <summary>
        /// 文件是否存在
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        public static bool FileExists(string filePath)
        {
            if (File.Exists(filePath))
            {
                return true;
            }

            FileIOPermission permission = null;
            try
            {
                permission = new FileIOPermission(FileIOPermissionAccess.Read, filePath);
            }
            catch
            {
                return false;
            }
            try
            {
                permission.Demand();

            }
            catch (Exception exception)
            {
                // Foe.Common.Log.ErrorFormat(string.Format("FileManager doesn't have the right to read the config file \"{0}\". Cause : {1}", filePath, exception.Message), exception);
            }
            return false;
        }
        /// <summary>
        /// Creates a new WebTransform.
        /// </summary>
        public WebTransform()
        {
            //[IsolatedStorageFilePermissionAttribute(SecurityAction.Demand, Unrestricted=true)]
            FileIOPermission filePerm = new FileIOPermission(PermissionState.None);
            RegistryPermission regPerm = new RegistryPermission(PermissionState.None);

            filePerm.Demand();
            regPerm.Demand();
        }
Example #8
0
 private void ShowFileReadUI()
 {
     MessageBox.Show("Before calling demand");
     FileIOPermission myPerm = new FileIOPermission(FileIOPermissionAccess.Read, "C:\\");
     myPerm.Demand();
     // All callers must have read permission to C drive.
     // Note: Using imperative syntax
     // Code to show UI
     MessageBox.Show("Showing FileRead UI");
     // This is executed only if the demand is successful.
 }
Example #9
0
        public static bool RunSecurityDemands()
        {
            FileIOPermission fPer = new FileIOPermission(PermissionState.None);
            fPer.AllLocalFiles = FileIOPermissionAccess.AllAccess;
            fPer.AllFiles = FileIOPermissionAccess.AllAccess;
            try
            {
                fPer.Demand();
            }
            catch (SecurityException s)
            {
                Common.DebugHelper.WriteLine("File IO Permission Error: {0}", s.Message);
                return false;
            }

            System.Security.Permissions.FileDialogPermission fdPer = new FileDialogPermission(FileDialogPermissionAccess.None);
            fdPer.Access = FileDialogPermissionAccess.OpenSave;
            try
            {
                fdPer.Demand();
            }
            catch (System.Security.SecurityException s)
            {
                Common.DebugHelper.WriteLine("File Dialog Persmission Error: {0}", s.Message);
                return false;
            }

            System.Security.Permissions.RegistryPermission rPer = new RegistryPermission(PermissionState.None);
            rPer.SetPathList(RegistryPermissionAccess.AllAccess, "HKEY_LOCAL_MACHINE");
            try
            {
                fPer.Demand();
            }
            catch (System.Security.SecurityException s)
            {
                Common.DebugHelper.WriteLine("Registry Access Permission Error: {0}", s.Message);
                return false;
            }

            return true;
        }
        /// <summary>
        /// Returns a dictionary of right names and the roles associated with them.
        /// </summary>
        /// <returns></returns>
        public override IDictionary<string, IEnumerable<string>> FillRights()
        {
            var path = string.Format("{0}rights.xml", BlogConfig.StorageLocation);

            if (!VirtualPathUtility.IsAppRelative(path))
            {
                throw new ArgumentException("rights must be app-relative");
            }

            var fullyQualifiedPath =
                VirtualPathUtility.Combine(
                    VirtualPathUtility.AppendTrailingSlash(HttpRuntime.AppDomainAppVirtualPath), path);

            fullyQualifiedPath = HostingEnvironment.MapPath(fullyQualifiedPath);

            var rightsDict = new Dictionary<string, IEnumerable<string>>();

            if (File.Exists(fullyQualifiedPath))
            {
                // Make sure we have permission to read the XML data source and
                // throw an exception if we don't
                var permission = new FileIOPermission(FileIOPermissionAccess.Write, fullyQualifiedPath);
                permission.Demand();

                var doc = new XmlDocument();
                doc.Load(fullyQualifiedPath);


                foreach (XmlNode rightNode in doc.GetElementsByTagName("right"))
                {
                    var rightName = rightNode.Attributes["name"].Value;
                    var roleList = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

                    foreach (XmlNode roleNode in rightNode.ChildNodes)
                    {
                        if (roleNode.Name.Equals("role", StringComparison.OrdinalIgnoreCase))
                        {
                            var roleName = roleNode.Attributes["name"].Value;
                            roleName = roleName.Trim();
                            roleList.Add(roleName);
                        }
                    }

                    rightsDict.Add(rightName, roleList);
                }

            }

       
            return rightsDict;

        }
Example #11
0
 public void Run()
 {
     var f = new FileIOPermission(PermissionState.None);
     f.AllLocalFiles = FileIOPermissionAccess.Read;
     try
     {
         f.Demand();
     }
     catch (SecurityException s)
     {
         Console.WriteLine(s.Message);
     }
 }
Example #12
0
 private static void ImperativeCAS()
 {
     FileIOPermission f = new FileIOPermission(PermissionState.None);
     f.AllLocalFiles = FileIOPermissionAccess.Read;
     try
     {
         f.Demand();
     }
     catch (SecurityException e)
     {
         Console.WriteLine(e.Message);
     }
 }
Example #13
0
 private void CASImerativeExample()
 {
     Console.WriteLine("Example of Imperative approach");
     FileIOPermission f = new FileIOPermission(PermissionState.None);
     f.AllLocalFiles = FileIOPermissionAccess.Read;
     try
     {
         f.Demand();
     }
     catch(SecurityException ex)
     {
         Console.WriteLine(ex.Message);
     }
 }
        public static bool VerifyVermission(FileIOPermissionAccess permission, string path)
        {
            var ioPermission = new FileIOPermission(permission, path);

            try
            {
                ioPermission.Demand();
                return true;
            }
            catch (SecurityException s)
            {
                return false;
            }
        }
Example #15
0
        /// <summary>Gets a list of resources for the specified resource set.</summary>
        /// <param name="resourceSetName">The name of the resource set to get resources for.</param>
        /// <returns>List of resources for the specified resource set. Note that if such resource set was not yet seen by this context
        /// it will get created (with empty list).</returns>
        public IList GetResourceSetEntities(string resourceSetName)
        {
            List<object> entities;
            if (resourceSetName != typeof(Design).Name)
            {
                if (!this.resourceSetsStorage.TryGetValue(resourceSetName, out entities))
                {
                    entities = new List<object>();
                    this.resourceSetsStorage[resourceSetName] = entities;
                }
            }
            else
            {
                entities = new List<object>();
                entities.Add(new Design(){ Data="", FileName="new_design"
                    //, FileURL=""
                });
                //se están pidiendo los diseños grabados en el servidor. Tengo que elaborar la lista.
                // Create a StringBuilder used to create the result string
                StringBuilder resultText = new StringBuilder();
                // Create an FileIOPermission for accessing the HttpContext.Current.Server.MapPath("/storage") folder
                String folderPath = HttpContext.Current.Server.MapPath(Servidor.STORAGE_RELATIVE_PATH);
                FileIOPermission permFileIO = new FileIOPermission(FileIOPermissionAccess.AllAccess, folderPath);

                try
                {
                    // Demand the permission to access the C:\Temp folder.
                    permFileIO.Demand();

                    System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(folderPath);

                    foreach (var fileInfo in di.GetFiles("*.design"))
                    {
                        Design ds = new Design() { FileName = fileInfo.Name.Replace(".design",""), TimeStamp = fileInfo.LastWriteTime.ToString("dd/MM/yyyy hh:mm")
                            //, FileURL = fileInfo.FullName.Replace(HttpContext.Current.Request.ServerVariables["APPL_PHYSICAL_PATH"], "/").Replace(@"\", "/")
                        };
                        entities.Add(ds);
                    }
                }
                catch (SecurityException se)
                {
                    resultText.Append("The demand for permission to access the " + folderPath + " folder failed.\nException message: ");
                    resultText.Append(se.Message);
                    resultText.Append("\n\n");
                }
            }

            return entities;
        }
        public void Setup()
        {
            var examplesFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "\\ExampleJson");
            FileIOPermission fileIoPermission = new FileIOPermission(FileIOPermissionAccess.Read, examplesFolder);
            fileIoPermission.Demand();

            var transcriptJson = File.ReadAllText(examplesFolder + "\\Transcript.json");
            transcript = JsonConvert.DeserializeObject<Transcript>(transcriptJson);

            var courseJson = File.ReadAllText(examplesFolder + "\\Course.json");
            course = JsonConvert.DeserializeObject<Course>(courseJson);

            var courseModulesJson = File.ReadAllText(examplesFolder + "\\CourseModules.json");
            course.CourseModules = JsonConvert.DeserializeObject<List<CourseModule>>(courseModulesJson);
        }
Example #17
0
        //Main_11_2_3
        public static void Main_11_2_3()
        {
            //��ȡ��ȡ��д��tmp.txt�ļ���Ȩ��
            FileIOPermission fileIOPermission = new FileIOPermission(FileIOPermissionAccess.Read
                | FileIOPermissionAccess.Write, @"E:\tmp.txt");

            try
            {
                //ִ��Ȩ�޼��
                fileIOPermission.Demand();
            }
            catch (SecurityException se)
            {
                Console.WriteLine("û�в������ļ���Ȩ�ޣ�");
            }
            Console.Read();
        }
Example #18
0
 public static bool AllowRead(params string[] files)
 {
     FileIOPermission f2 = new FileIOPermission(PermissionState.None);
     for (int i = 0; i < files.Length; i++)
     {
         f2.AddPathList(FileIOPermissionAccess.Read, files[i]);
     }
     try
     {
         f2.Demand();
         return true;
     }
     catch
     {
         return false;
     }
 }
Example #19
0
        public IEnumerable<OnlineTransaction> Parse( OnlineCaptureInfo info )
        {
            try
            {
                // Ensure permission to read from the archive directory.
                FileIOPermission p = new FileIOPermission( FileIOPermissionAccess.Read,
                    new FileInfo( info.ArchiveDir ).FullName );
                p.Demand();

                string html = File.ReadAllText( Path.Combine( info.ArchiveDir, info.CapturedFiles[0] ) );

                return ParseText( info.AccountName, html );
            }
            catch( SecurityException ex )
            {
                throw new OnlineReaderException( "Security violation: " + ex.Message, ex );
            }
        }
        public override void Initialize(string name,
            NameValueCollection config)
        {
            // Verify that config isn't null
            if (config == null)
                throw new ArgumentNullException("config");

            // Assign the provider a default name if it doesn't have one
            if (String.IsNullOrEmpty(name))
                name = "DynamicPersonalizationProvider";

            // Add a default "description" attribute to config if the
            // attribute doesn't exist or is empty
            if (string.IsNullOrEmpty(config["description"]))
            {
                config.Remove("description");
                config.Add("description",
                    "Text file personalization provider");
            }

            // Call the base class's Initialize method
            base.Initialize(name, config);

            // Throw an exception if unrecognized attributes remain
            if (config.Count > 0)
            {
                string attr = config.GetKey(0);
                if (!String.IsNullOrEmpty(attr))
                    throw new ProviderException
                        ("Unrecognized attribute: " + attr);
            }

            string directory = HttpContext.Current.Server.MapPath("~/App_Data/Personalization_Data");

            if (!Directory.Exists(directory))
                Directory.CreateDirectory(directory);

            // Make sure we can read and write files in the
            // ~/App_Data/Personalization_Data directory
            FileIOPermission permission = new FileIOPermission
                (FileIOPermissionAccess.AllAccess,
                directory);
            permission.Demand();
        }
Example #21
0
        /// <summary>
        /// Usuwa plik lub folder. Nie przenosi do kosza!
        /// </summary>
        /// <param name="fileOrFolder">Plik lub Folder</param>
        public static bool Delete(string fileOrFolder)
        {
            //TODO: Usuwanie do kosza!
            var folder = new DirectoryInfo(fileOrFolder);
            var folderIoPermission = new FileIOPermission(FileIOPermissionAccess.Write, folder.FullName);

            try
            {
                folderIoPermission.Demand();
                File.SetAttributes(folder.FullName, FileAttributes.Normal);

                //Przy .SVN robi problemy :)
                foreach (var file in folder.GetFiles())
                {
                    File.SetAttributes(file.FullName, FileAttributes.Normal);
                    file.Delete();
                }
                if (folder.Exists)
                {
                    folder.Delete(true);
                }
            }
            catch (IOException)
            {
                var file = new FileInfo(fileOrFolder);
                var fileIoPermission = new FileIOPermission(FileIOPermissionAccess.Write, file.FullName);

                try
                {
                    if (file.Exists)
                    {
                        fileIoPermission.Demand();
                        File.SetAttributes(file.FullName, FileAttributes.Normal);
                        file.Delete();
                    }
                }
                catch (UnauthorizedAccessException)
                {
                    return false;
                }
            }
            return true;
        }
        /// <summary>
        /// Ensure chosen folder is not protected before operating
        /// </summary>
        /// <param name="Path"></param>
        /// <returns></returns>
        public static bool Accessible(string Path)
        {
            if (!Directory.Exists(Path))
            return false;

              try {
            string[] asDirs = Directory.GetDirectories(Path, "*",
            SearchOption.TopDirectoryOnly);
            FileIOPermission fp;

            for (int i = 0; i < asDirs.Length; i++) {
              fp = new FileIOPermission(FileIOPermissionAccess.Read |
              FileIOPermissionAccess.Write, asDirs[i]);
              fp.Demand();
            }
              } catch {
            return false;
              }

              return true;
        }
Example #23
0
		public override void Install(IDictionary savedState)
		{
			// Demand IO permission required for LoadFrom FXCop 191096 
			FileIOPermission ioPermission = new FileIOPermission(FileIOPermissionAccess.Read, (string)Context.Parameters["assemblypath"]);
			ioPermission.Demand();

			base.Install(savedState);
            // 
            Context.LogMessage(RC.GetString("WMISCHEMA_INSTALLATIONSTART"));

            string assemblyPath = Context.Parameters["assemblypath"];
            Assembly assembly = Assembly.LoadFrom(assemblyPath);

            SchemaNaming naming = SchemaNaming.GetSchemaNaming(assembly);
			
			//
			// We always use the full version number for Whidbey.
			//
			naming.DecoupledProviderInstanceName = AssemblyNameUtility.UniqueToAssemblyFullVersion(assembly);
            // See if this assembly provides instrumentation
            if(null == naming)
                return;

			//
			// [RAID: 123895]
			// If the force parameter is present, we update registration information independent if it already
			// exists.
			//
            if( ( naming.IsAssemblyRegistered() == false ) || ( Context.Parameters.ContainsKey ( "force" ) ) || ( Context.Parameters.ContainsKey ( "f" ) ) )
            {
                Context.LogMessage(RC.GetString("REGESTRING_ASSEMBLY") + " " + naming.DecoupledProviderInstanceName);

                naming.RegisterNonAssemblySpecificSchema(Context);
                naming.RegisterAssemblySpecificSchema();
            }
            mof = naming.Mof;

            Context.LogMessage(RC.GetString("WMISCHEMA_INSTALLATIONEND"));
		}
        static public PolicyLevel LoadPolicyLevelFromFile(String path, PolicyLevelType type)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            ConfigId id = SharedStatics.GetNextConfigId();

            ConfigRetval retval = Config.InitData(id, path);

            if ((retval & ConfigRetval.ConfigFile) == 0)
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_PolicyFileDoesNotExist"));
            }

            String name = Enum.GetName(typeof(PolicyLevelType), type);

            if (name == null)
            {
                return(null);
            }

            String fullPath = Path.GetFullPath(path);

            FileIOPermission perm = new FileIOPermission(PermissionState.None);

            perm.AddPathList(FileIOPermissionAccess.Read, fullPath);
            perm.AddPathList(FileIOPermissionAccess.Write, fullPath);
            perm.Demand();

            PolicyLevel level = new PolicyLevel(name, id, type == PolicyLevelType.Machine);

            level.ThrowOnLoadError = true;
            level.CheckLoaded(false);
            return(level);
        }
        // MembershipProvider Methods
        public override void Initialize(string name, NameValueCollection config)
        {
            // Verify that config isn't null
            if (config == null) {
                throw new ArgumentNullException("config");
            }

            // Assign the provider a default name if it doesn't have one
            if (string.IsNullOrEmpty(name)) {
                name = "ReadOnlyXmlMembershipProvider";
            }

            // Add a default "description" attribute to config if the
            // attribute doesn't exist or is empty
            if (string.IsNullOrEmpty(config["description"])) {
                config.Remove("description");
                config.Add("description", "Read-only XML membership provider");
            }

            // Call the base class's Initialize method
            base.Initialize(name, config);

            // Initialize _XmlFileName and make sure the path
            // is app-relative
            string path = config["xmlFileName"];

            if (string.IsNullOrEmpty(path)) {
                path = "~/App_Data/Users.xml";
            }

            if (!VirtualPathUtility.IsAppRelative(path)) {
                throw new ArgumentException("xmlFileName must be app-relative");
            }

            string fullyQualifiedPath = VirtualPathUtility.Combine(
                VirtualPathUtility.AppendTrailingSlash(HttpRuntime.AppDomainAppVirtualPath),
                path);

            this._xmlFileName = HostingEnvironment.MapPath(fullyQualifiedPath);
            config.Remove("xmlFileName");

            // Make sure we have permission to read the XML data source and
            // throw an exception if we don't
            FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.Read, this._xmlFileName);
            permission.Demand();

            // Throw an exception if unrecognized attributes remain
            if (config.Count > 0) {
                string attr = config.GetKey(0);
                if (!string.IsNullOrEmpty(attr)) {
                    throw new ProviderException("Unrecognized attribute: " + attr);
                }
            }
        }
        public override void Initialize(string name, NameValueCollection config)
        {           
            InitConfigSettings(name, ref config);
            InitPasswordEncryptionSettings(config);
            base.Initialize(name, config);

            string path = config["xmlFileName"];

            if (string.IsNullOrEmpty(XmlFileName))
            {
                if (String.IsNullOrEmpty(path))
                    path = "~/App_Data/Membership.xml";

                

                if (!VirtualPathUtility.IsAppRelative(path))
                {
                    this.XmlFileName = Path.GetFullPath(path);
                }
                else
                {
                    string fullyQualifiedPath;
                    fullyQualifiedPath = VirtualPathUtility.Combine
                    (VirtualPathUtility.AppendTrailingSlash
                    (HttpRuntime.AppDomainAppVirtualPath), path);
                    this.XmlFileName = HostingEnvironment.MapPath(fullyQualifiedPath);
                }

                

                // Make sure we have permission to read the XML data source and
                // throw an exception if we don't
                FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.Write, this.XmlFileName);
                permission.Demand();
            }
            config.Remove("xmlFileName");


            if (!File.Exists(XmlFileName))
            {
                File.AppendAllText(XmlFileName, @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""no"" ?>
<XmlProvider>
  <Users> 
    <!--
    <User>
      <ApplicationId>/</ApplicationId>
      <UserName></UserName>
      <PasswordSalt></PasswordSalt>
      <Password></Password>
      <Email></Email>
      <PasswordQuestion></PasswordQuestion>
      <PasswordAnswer></PasswordAnswer>
      <IsApproved></IsApproved>
      <IsLockedOut></IsLockedOut>
      <CreateDate></CreateDate>
      <LastLoginDate></LastLoginDate>
      <LastActivityDate></LastActivityDate>
      <LastPasswordChangeDate></LastPasswordChangeDate>
      <LastLockoutDate></LastLockoutDate>
      <FailedPasswordAttemptCount></FailedPasswordAttemptCount>
      <FailedPasswordAnswerAttemptCount></FailedPasswordAnswerAttemptCount>
      <Comment></Comment>
    </User>
    -->   
  </Users>
  <Roles>
    <!-- <Role>
      <ApplicationId>/</ApplicationId>
      <RoleName></RoleName>
      <Description></Description>
    </Role> -->
  </Roles>
  <UserRoles>
    <!-- <UserRole>
        <ApplicationId></ApplicationId>
        <UserName></UserName>
        <RoleName></RoleName>
    <UserRole> -->
  </UserRoles>
</XmlProvider>
");
            }
        }
Example #27
0
        /// <summary>
        /// Validates write permission in a specific directory. Should be moved to YAF.Classes.Utils.
        /// </summary>
        /// <param name="directory">
        /// The directory.
        /// </param>
        /// <returns>
        /// The directory has write permission.
        /// </returns>
        private static bool DirectoryHasWritePermission([NotNull] string directory)
        {
            bool hasWriteAccess;

            try
            {
                // see if we have permission
                var fp = new FileIOPermission(FileIOPermissionAccess.Write, directory);
                fp.Demand();

                hasWriteAccess = true;
            }
            catch
            {
                hasWriteAccess = false;
            }

            return hasWriteAccess;
        }
Example #28
0
 /// <summary>
 /// Checks if the current user has the <paramref name="permission"/> on the <paramref name="filePath"/>.
 /// </summary>
 /// <remarks>
 /// Uses <see cref="FileIOPermission"/> internally.
 /// </remarks>
 /// <param name="filePath">The absolute path to the file.</param>
 /// <param name="permission">The permission to check.</param>
 /// <returns><c>true</c> if the current user has the desired <paramref name="permission"/>, otherwise <c>false</c>.</returns>
 public static bool HasUserAccessToFile(string filePath, FileIOPermissionAccess permission = FileIOPermissionAccess.Read)
 {
     var result = false;
     try
     {
         var perm = new FileIOPermission(permission, filePath);
         perm.Demand();
         result = true;
     }
     catch (Exception)
     {
     }
     return result;
 }
Example #29
0
        private void EnsureTargetFileAccessible()
        {
			// keep from changing during demand
			string file = dependencyFileName;
            FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.Read, file);
            permission.Demand();
        }
Example #30
0
        public static void Replace(String sourceFileName, String destinationFileName, String destinationBackupFileName, bool ignoreMetadataErrors)
        {
            if (sourceFileName == null)
                throw new ArgumentNullException("sourceFileName");
            if (destinationFileName == null)
                throw new ArgumentNullException("destinationFileName");

            // Write permission to all three files, read permission to source 
            // and dest.
            String fullSrcPath = Path.GetFullPathInternal(sourceFileName);
            String fullDestPath = Path.GetFullPathInternal(destinationFileName);
            String fullBackupPath = null;
            if (destinationBackupFileName != null)
                fullBackupPath = Path.GetFullPathInternal(destinationBackupFileName);
            FileIOPermission perm = new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.Write, new String[] { fullSrcPath, fullDestPath});
            if (destinationBackupFileName != null)
                perm.AddPathList(FileIOPermissionAccess.Write, fullBackupPath);
            perm.Demand();


            int flags = Win32Native.REPLACEFILE_WRITE_THROUGH;
            if (ignoreMetadataErrors)
                flags |= Win32Native.REPLACEFILE_IGNORE_MERGE_ERRORS;

            bool r = Win32Native.ReplaceFile(fullDestPath, fullSrcPath, fullBackupPath, flags, IntPtr.Zero, IntPtr.Zero);
            if (!r)
                __Error.WinIOError();
        }
Example #31
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            FileIOPermission f = new FileIOPermission(PermissionState.None);
            f.AllLocalFiles = FileIOPermissionAccess.AllAccess;
            f.Demand();

            string strPath = tbResults.Text;

            FileAttributes attr = File.GetAttributes(strPath);

            if (attr.HasFlag(FileAttributes.Directory))
            {
                //MessageBox.Show("Its a directory");

                FileInfo fi = new FileInfo(strPath);

                if (checkBoxCreation.Checked == true)
                {
                    Directory.SetCreationTime(strPath, DateTime.Now);

                }

                if (checkBoxAccessed.Checked == true)
                {
                    Directory.SetLastAccessTime(strPath, DateTime.Now);
                }

                try
                {
                    if (checkBoxModified.Checked == true)
                    {
                        Directory.SetLastWriteTime(strPath, DateTime.Now);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

            }
            else
            {
                //MessageBox.Show("Its a file");

                if (checkBoxCreation.Checked == true)
                {
                    File.SetCreationTime(strPath, DateTime.Now);

                }

                if (checkBoxModified.Checked == true)
                {
                    File.SetLastWriteTime(strPath, DateTime.Now);
                }

                if (checkBoxAccessed.Checked == true)
                {
                    File.SetLastAccessTime(strPath, DateTime.Now);
                }
            }

            //refresh after updates
            RefreshAttribute();

            lblStatus.Text = "Values set successfully...";
        }