当前位置: 首页>>代码示例>>C#>>正文


C# FileIOPermission.Assert方法代码示例

本文整理汇总了C#中System.Security.Permissions.FileIOPermission.Assert方法的典型用法代码示例。如果您正苦于以下问题:C# FileIOPermission.Assert方法的具体用法?C# FileIOPermission.Assert怎么用?C# FileIOPermission.Assert使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Security.Permissions.FileIOPermission的用法示例。


在下文中一共展示了FileIOPermission.Assert方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Setup

 public virtual void Setup()
 {
     var sp = new FileIOPermission(PermissionState.Unrestricted);
     sp.Assert();
     string prefix;
     if (Environment.CurrentDirectory.EndsWith("target"))
     {
         prefix = "../../";
     }
     else
     {
         prefix = "../../../";
     }
     sp.Deny();
     Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
     BridgeSetup setup=new BridgeSetup (false){Verbose = true, Debug = true};
     setup.IgnoreJavaHome = true;
     setup.AddJVMOption("-Xmx512m");
     setup.AddClassPath(prefix + "jni4net.j/target/classes");
     setup.AddClassPath(prefix + "jni4net.tested.j/target/classes");
     setup.AddClassPath(prefix + "jni4net.test.j/target/test-classes");
     //setup.JavaHome = @"c:\Program Files (x86)\Java\ibm_sdk60";
     env = Bridge.CreateJVM(setup);
     Bridge.RegisterAssembly(typeof(TestBase).Assembly);
     Bridge.RegisterAssembly(typeof(JavaInstanceFields).Assembly);
 }
开发者ID:Mazrick,项目名称:jni4net,代码行数:26,代码来源:TestBase.cs

示例2: EnsureActivateContextCreated

		bool EnsureActivateContextCreated()
		{
			lock (typeof(EnableThemingInScope))
			{
				if (!contextCreationSucceeded)
				{
					// Pull manifest from the .NET Framework install
					// directory

					string assemblyLoc = null;

					FileIOPermission fiop = new FileIOPermission(PermissionState.None);
					fiop.AllFiles = FileIOPermissionAccess.PathDiscovery;
					fiop.Assert();
					try
					{
						assemblyLoc = typeof(Object).Assembly.Location;
					}
					finally
					{
						CodeAccessPermission.RevertAssert();
					}

					string manifestLoc = null;
					string installDir = null;
					if (assemblyLoc != null)
					{
						installDir = Path.GetDirectoryName(assemblyLoc);
						const string manifestName = "XPThemes.manifest";
						manifestLoc = Path.Combine(installDir, manifestName);
					}

					if (manifestLoc != null && installDir != null)
					{
						enableThemingActivationContext = new ACTCTX();
						enableThemingActivationContext.cbSize = Marshal.SizeOf(typeof(ACTCTX));
						enableThemingActivationContext.lpSource = manifestLoc;

						// Set the lpAssemblyDirectory to the install
						// directory to prevent Win32 Side by Side from
						// looking for comctl32 in the application
						// directory, which could cause a bogus dll to be
						// placed there and open a security hole.
						enableThemingActivationContext.lpAssemblyDirectory = installDir;
						enableThemingActivationContext.dwFlags = ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID;

						// Note this will fail gracefully if file specified
						// by manifestLoc doesn't exist.
						hActCtx = CreateActCtx(ref enableThemingActivationContext);
						contextCreationSucceeded = (hActCtx != new IntPtr(-1));
					}
				}

				// If we return false, we'll try again on the next call into
				// EnsureActivateContextCreated(), which is fine.
				return contextCreationSucceeded;
			}
		}
开发者ID:mhusen,项目名称:Eto,代码行数:58,代码来源:EnableThemingInScope.cs

示例3: DoesCallerRequireFullTrust

 private static bool DoesCallerRequireFullTrust(MethodInfo method){
   Assembly assembly = method.DeclaringType.Assembly;
   // strongly-named assembly requires full trust or AllowPartiallyTrustedCallersAttribute to be called
   FileIOPermission pathDiscoveryPermission = new FileIOPermission(PermissionState.None);
   pathDiscoveryPermission.AllFiles = FileIOPermissionAccess.PathDiscovery;
   pathDiscoveryPermission.Assert();
   byte[] key = assembly.GetName().GetPublicKey();
   if (key == null || key.Length == 0)
     return false;
   if (CustomAttribute.GetCustomAttributes(assembly, typeof(AllowPartiallyTrustedCallersAttribute), true).Length != 0)
     return false;
   return true;
 }
开发者ID:gbarnett,项目名称:shared-source-cli-2.0,代码行数:13,代码来源:methodinvoker.cs

示例4: UnsafeGetFullPath

        public static string UnsafeGetFullPath(string fileName) {
            string full = fileName;

            FileIOPermission fiop = new FileIOPermission(PermissionState.None);
            fiop.AllFiles = FileIOPermissionAccess.PathDiscovery;
            fiop.Assert();
            try {
                full = System.IO.Path.GetFullPath(fileName);
            }
            finally {
                CodeAccessPermission.RevertAssert();
            }
            return full;
        }
开发者ID:iskiselev,项目名称:JSIL.NetFramework,代码行数:14,代码来源:IntSecurity.cs

示例5: Save

 public static void Save(string value)
 {
     try
      {
     FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.Append,@"c:\audit.txt");
     permission.Assert();
     FileStream stream = new FileStream(@"c:\audit.txt",FileMode.Append, FileAccess.Write);
     // code to write to audit file here...
     CodeAccessPermission.RevertAssert();
     Console.WriteLine("Data written to audit file");
      }
      catch
      {
     Console.WriteLine("Failed to write data to audit file");
      }
 }
开发者ID:alannet,项目名称:example,代码行数:16,代码来源:Class1.cs

示例6: Session_MessageReceived

        void Session_MessageReceived(object sender, MessageEventArgs e)
        {
            // Save the message in the preset pickup directory
            // ensure we can write
            FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.Write, DumpPath);
            permission.Assert();

            StreamWriter file
                = File.AppendText(DumpPath);
            try
            {
                file.Write(_LineTerminator + "---------------START OF MESSAGE-------------------" + _LineTerminator);
                file.Write("Message Id: " + e.MessageId + _LineTerminator);
                file.Write(_LineTerminator + "From: " + e.From + _LineTerminator);
                file.Write("To: " + e.ToAsList() + _LineTerminator);
                file.Write(_LineTerminator + "Subject: " + e.Subject + _LineTerminator);
                file.Write("Data: " + e.Data + _LineTerminator);
                file.Write(_LineTerminator + "---------------END OF MESSAGE---------------------" + _LineTerminator);
                file.Close();

                SetStatus(String.Format("Recieved: {0}", e.Subject));
            }
            finally { file.Close(); }
        }
开发者ID:netflakes,项目名称:smtp-faker,代码行数:24,代码来源:SmtpServer.cs

示例7: EnsureActCtxCreated

        private static bool EnsureActCtxCreated()
        {
            lock(m_oSync)
            {
                if(m_nhCtx.HasValue) return true;

                string strAsmLoc;
                FileIOPermission p = new FileIOPermission(PermissionState.None);
                p.AllFiles = FileIOPermissionAccess.PathDiscovery;
                p.Assert();
                try { strAsmLoc = typeof(object).Assembly.Location; }
                finally { CodeAccessPermission.RevertAssert(); }
                if(string.IsNullOrEmpty(strAsmLoc)) { Debug.Assert(false); return false; }

                string strInstDir = Path.GetDirectoryName(strAsmLoc);
                string strMfLoc = Path.Combine(strInstDir, "XPThemes.manifest");

                NativeMethods.ACTCTX ctx = new NativeMethods.ACTCTX();
                ctx.cbSize = (uint)Marshal.SizeOf(typeof(NativeMethods.ACTCTX));
                Debug.Assert(((IntPtr.Size == 4) && (ctx.cbSize ==
                    NativeMethods.ACTCTXSize32)) || ((IntPtr.Size == 8) &&
                    (ctx.cbSize == NativeMethods.ACTCTXSize64)));

                ctx.lpSource = strMfLoc;
                ctx.lpAssemblyDirectory = strInstDir;
                ctx.dwFlags = NativeMethods.ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID;

                m_nhCtx = NativeMethods.CreateActCtx(ref ctx);
                if(NativeMethods.IsInvalidHandleValue(m_nhCtx.Value))
                {
                    Debug.Assert(false);
                    m_nhCtx = null;
                    return false;
                }
            }

            return true;
        }
开发者ID:earthday,项目名称:keepass2,代码行数:38,代码来源:EnableThemingInScope.cs

示例8: Dispose

        /// <include file='doc\ListView.uex' path='docs/doc[@for="ListView.Dispose"]/*' />
        /// <devdoc>
        ///     Disposes of the component.  Call dispose when the component is no longer needed.
        ///     This method removes the component from its container (if the component has a site)
        ///     and triggers the dispose event.
        /// </devdoc>
        protected override void Dispose(bool disposing) {
            if (disposing) {
                // Remove any event sinks we have hooked up to imageLists
                if (imageListSmall != null) {
                    imageListSmall.Disposed -= new EventHandler(this.DetachImageList);
                    imageListSmall = null;
                }
                if (imageListLarge != null) {
                    imageListLarge.Disposed -= new EventHandler(this.DetachImageList);
                    imageListLarge = null;
                }
                if (imageListState != null) {
                    imageListState.Disposed -= new EventHandler(this.DetachImageList);
                    imageListState = null;
                }

                // Remove any ColumnHeaders contained in this control
                if (columnHeaders != null) {
                    for (int colIdx = columnHeaders.Length-1; colIdx >= 0; colIdx--) {
                        columnHeaders[colIdx].OwnerListview = null;
                        columnHeaders[colIdx].Dispose();
                    }
                    columnHeaders = null;
                }

                // Remove any items we have
                Items.Clear();

                if (odCacheFontHandleWrapper != null)
                {
                    odCacheFontHandleWrapper.Dispose();
                    odCacheFontHandleWrapper = null;
                }

                if (!String.IsNullOrEmpty(this.backgroundImageFileName) || this.bkImgFileNames != null) {
                    // we need the fileIoPermission when the app runs on an UNC share and
                    // the list view creates/deletes temporary files for its background image
                    
                    // SECREVIEW : Safe to assert FileIO here since we are deleting files created by us.
                    //
                    FileIOPermission fiop = new FileIOPermission(PermissionState.Unrestricted);
                    fiop.Assert();

                    try {
                        System.IO.FileInfo fi;
                        if (!String.IsNullOrEmpty(this.backgroundImageFileName)) {
                            fi = new System.IO.FileInfo(this.backgroundImageFileName);
                            Debug.Assert(fi.Exists, "who deleted our temp file?");
                            // [....]: vsWhidbey 417804.
                            // ComCtl ListView uses COM objects to manipulate the bitmap we send it to them.
                            // I could not find any resources which explain in detail when the IImgCtx objects
                            // release the temporary file. So if we get a FileIO when we delete the temporary file
                            // we don't do anything about it ( because we don't know what is a good time to try to delete the file again ).
                            try {
                                fi.Delete();
                            } catch (System.IO.IOException){}
                            this.backgroundImageFileName = String.Empty;
                        }
                        for (int i = 0; i <= this.bkImgFileNamesCount; i++) {
                            fi = new System.IO.FileInfo(this.bkImgFileNames[i]);
                            Debug.Assert(fi.Exists, "who deleted our temp file?");
                            // [....]: vsWhidbey 417804.
                            // ComCtl ListView uses COM objects to manipulate the bitmap we send it to them.
                            // I could not find any resources which explain in detail when the IImgCtx objects
                            // release the temporary file. So if we get a FileIO when we delete the temporary file
                            // we don't do anything about it ( because we don't know what is a good time to try to delete the file again ).
                            try {
                                fi.Delete();
                            } catch (System.IO.IOException){}
                        }

                        this.bkImgFileNames = null;
                        this.bkImgFileNamesCount = -1;
                    } finally {
                        System.Security.PermissionSet.RevertAssert();
                    }
                }

            }

            base.Dispose(disposing);
        }
开发者ID:JianwenSun,项目名称:cc,代码行数:88,代码来源:ListView.cs

示例9: DeleteFileName

 private void DeleteFileName(string fileName) {
     if (!String.IsNullOrEmpty(fileName)) {
         // the list view needs the FileIOPermission when the app runs on an UNC share
         // and the list view creates / destroys temporary files for its background image
         
         // SECREVIEW : Safe to assert FileIO here since we are deleting files created by us.
         //
         FileIOPermission fiop = new FileIOPermission(PermissionState.Unrestricted);
         fiop.Assert();
         try {
             System.IO.FileInfo fi = new System.IO.FileInfo(fileName);
             if (fi.Exists) {
                 // [....]: vsWhidbey 417804.
                 // ComCtl ListView uses COM objects to manipulate the bitmap we send it to them.
                 // I could not find any resources which explain in detail when the IImgCtx objects
                 // release the temporary file. So if we get a FileIO when we delete the temporary file
                 // we don't do anything about it ( because we don't know what is a good time to try to delete the file again ).
                 try {
                     fi.Delete();
                 } catch (System.IO.IOException){}
             }
         } finally {
             System.Security.PermissionSet.RevertAssert();
         }
     }
 }
开发者ID:JianwenSun,项目名称:cc,代码行数:26,代码来源:ListView.cs

示例10: IsAssemblyLoaded

        private static bool IsAssemblyLoaded(String assemblyName)
        {
            // Since there is no managed API for finding the GAC path, I 
            // assert path discovery for all local files.
            FileIOPermission permission = new FileIOPermission(PermissionState.None);
            permission.AllLocalFiles = FileIOPermissionAccess.PathDiscovery;
            permission.Assert();

            foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                if (assembly.FullName.Equals(assemblyName, StringComparison.OrdinalIgnoreCase)) {
                    return true;
                }

                // Warn if they have the same assembly with different versions.  If we don't do this,
                // they will get an InvalidCastException instead.
                AssemblyName name1 = new AssemblyName(assemblyName);
                AssemblyName name2 = assembly.GetName();
                if (name1.Name == name2.Name && 
                    name1.CultureInfo.Equals(name2.CultureInfo) &&
                    Utils.PublicKeyMatches(name1, name2) && 
                    name1.Version != name2.Version)
                {
                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Res.IncompatibleAddInBaseAssembly, assemblyName));
                }
            }
            return false;
        }
开发者ID:nlh774,项目名称:DotNetReferenceSource,代码行数:28,代码来源:ActivationWorker.cs

示例11: EnableVisualStyles

        /// <include file='doc\Application.uex' path='docs/doc[@for="Application.EnableVisualStyles"]/*' />
        /// <devdoc>
        ///    <para>
        ///    Enables visual styles for all subsequent Application.Run() and CreateHandle() calls.
        ///    Uses the default theming manifest file shipped with the redist.
        ///    </para>
        /// </devdoc>
        public static void EnableVisualStyles() {
            string assemblyLoc = null;

            // SECREVIEW : This Assert is ok, getting the module path is a safe operation, 
            //             the result is provided by the system.
            //
            FileIOPermission fiop = new FileIOPermission(PermissionState.None);
            fiop.AllFiles = FileIOPermissionAccess.PathDiscovery;
            fiop.Assert();
            try {
                assemblyLoc = typeof(Application).Assembly.Location;
            }
            finally {
                CodeAccessPermission.RevertAssert();
            }
            // Pull manifest from our resources
            if (assemblyLoc != null) {
                EnableVisualStylesInternal(assemblyLoc, 101);
            }
        }
开发者ID:nlh774,项目名称:DotNetReferenceSource,代码行数:27,代码来源:Application.cs

示例12: StaticWriteCompleted

        // Parameters:
        //  assertPermissions - If true, then we'll assert all required permissions.  Used by ClientSettingsConfigurationHost.
        //                      to allow low-trust apps to use ClientSettingsStore.
        static internal void StaticWriteCompleted(string streamName, bool success, object writeContext, bool assertPermissions) {
            WriteFileContext    writeFileContext = (WriteFileContext) writeContext;
            bool                revertAssert = false;

            if (assertPermissions) {
                 // If asked to assert permissions, we will assert allAccess on the streamName, the temporary file 
                // created by WriteContext, and also the directory itself.  The last one is needed because 
                // WriteFileContext will call TempFileCollection.Dispose, which will remove a .tmp file it created.
                string dir = Path.GetDirectoryName(streamName);
                string[] filePaths = new string[] {streamName, writeFileContext.TempNewFilename, dir};
                FileIOPermission fileIOPerm = new FileIOPermission(FileIOPermissionAccess.AllAccess, AccessControlActions.View | AccessControlActions.Change, filePaths);
                fileIOPerm.Assert();
                revertAssert = true;
            }

            try {
                writeFileContext.Complete(streamName, success);
            }
            finally {
                if (revertAssert) {
                    CodeAccessPermission.RevertAssert();
                }
            }
        }
开发者ID:nlh774,项目名称:DotNetReferenceSource,代码行数:27,代码来源:InternalConfigHost.cs

示例13: CreateSymbolFile

        private static void CreateSymbolFile(CounterCreationDataCollection creationData) {
            //SECREVIEW: PerformanceCounterPermission must have been demanded before
            FileIOPermission permission = new FileIOPermission(PermissionState.Unrestricted);
            permission.Assert();
            try {
                StreamWriter symbolWriter = new StreamWriter(SymbolFilePath);
                try {
                    symbolWriter.Write(defineKeyword);
                    symbolWriter.Write(" ");
                    symbolWriter.Write(categorySymbolPrefix);
                    symbolWriter.WriteLine("1 0;");

                    for (int counterIndex = 1; counterIndex <= creationData.Count; ++ counterIndex) {
                        symbolWriter.Write(defineKeyword);
                        symbolWriter.Write(" ");
                        symbolWriter.Write(conterSymbolPrefix);
                        symbolWriter.Write(counterIndex.ToString(CultureInfo.InvariantCulture));
                        symbolWriter.Write(" ");
                        symbolWriter.Write((counterIndex * 2).ToString(CultureInfo.InvariantCulture));
                        symbolWriter.WriteLine(";");
                    }

                    symbolWriter.WriteLine("");
                }
                finally {
                    symbolWriter.Close();
                }
            }
            finally {
                FileIOPermission.RevertAssert();
            }
        }
开发者ID:nlh774,项目名称:DotNetReferenceSource,代码行数:32,代码来源:PerformanceCounterLib.cs

示例14: ExecuteTask

        protected override void ExecuteTask()
        {
            ArrayList taskTypes;
            ArrayList dataTypes;

            if (ForType == null) {
                taskTypes = new ArrayList(TypeFactory.TaskBuilders.Count);
                dataTypes = new ArrayList(TypeFactory.DataTypeBuilders.Count);

                foreach (TaskBuilder tb in TypeFactory.TaskBuilders) {
                    taskTypes.Add(Assembly.LoadFrom(tb.AssemblyFileName).GetType(tb.ClassName, true, true));
                }

                foreach (DataTypeBaseBuilder db in TypeFactory.DataTypeBuilders) {
                    dataTypes.Add(Assembly.LoadFrom(db.AssemblyFileName).GetType(db.ClassName, true, true));
                }
            } else {
                taskTypes = new ArrayList(1);
                taskTypes.Add(Type.GetType(ForType, true, true));
                dataTypes = new ArrayList();
            }

            FileIOPermission FilePermission = new FileIOPermission(FileIOPermissionAccess.AllAccess, OutputFile.FullName); 
            FilePermission.Assert();
            using (FileStream file = File.Open(OutputFile.FullName, FileMode.Create, FileAccess.Write, FileShare.Read)) {
                WriteSchema(file, (Type[]) taskTypes.ToArray(typeof(Type)),
                    (Type[]) dataTypes.ToArray(typeof(Type)), TargetNamespace);

                file.Flush();
                file.Close();
            }

            Log(Level.Info, "Wrote schema to '{0}'.", OutputFile.FullName);
开发者ID:vardars,项目名称:ci-factory,代码行数:33,代码来源:NAntSchemaTask.cs

示例15: ExecuteTask

        protected override void ExecuteTask()
        {
            ArrayList taskTypes;
            ArrayList dataTypes;

            if (ForType == null) {
                taskTypes = new ArrayList(TypeFactory.TaskBuilders.Count);
                dataTypes = new ArrayList(TypeFactory.DataTypeBuilders.Count);

                foreach (TaskBuilder tb in TypeFactory.TaskBuilders) {
                    taskTypes.Add(tb.Assembly.GetType(tb.ClassName, true, true));
                }

                foreach (DataTypeBaseBuilder db in TypeFactory.DataTypeBuilders) {
                    dataTypes.Add(db.Assembly.GetType(db.ClassName, true, true));
                }
            } else {
                taskTypes = new ArrayList(1);
                taskTypes.Add(Type.GetType(ForType, true, true));
                dataTypes = new ArrayList();
            }

            MemoryStream ms = new MemoryStream();
            WriteSchema(ms, (Type[]) taskTypes.ToArray(typeof(Type)),
                (Type[]) dataTypes.ToArray(typeof(Type)), TargetNamespace);

            // reset position of memorystream
            ms.Position = 0;

            // let's validate whether we emitted a valid XML Schema
            try {
                XmlSchema schema = XmlSchema.Read(ms, null);
                schema.Compile(null);
            } catch (XmlSchemaException ex) {
                throw new BuildException ("The generated XML schema is not valid.",
                    Location, ex);
            }
            // reset position of memorystream
            ms.Position = 0;
            FileIOPermission FilePermission = new FileIOPermission(FileIOPermissionAccess.AllAccess, OutputFile.FullName);
            FilePermission.Assert();
            using (FileStream file = File.Open(OutputFile.FullName, FileMode.Create, FileAccess.Write, FileShare.Read)) {
                byte[] buffer = new byte[4096];
                int bytesRead = ms.Read(buffer, 0, buffer.Length);
                while (bytesRead != 0) {
                    file.Write(buffer, 0, bytesRead);
                    bytesRead = ms.Read(buffer, 0, buffer.Length);
                }
                file.Flush();
                file.Close();
            }

            Log(Level.Info, "Wrote schema to '{0}'.", OutputFile.FullName);
        }
开发者ID:julianhaslinger,项目名称:nant,代码行数:54,代码来源:NAntSchemaTask.cs


注:本文中的System.Security.Permissions.FileIOPermission.Assert方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。