In this procedure, you install the FileIO assembly in the global assembly cache (GAC). You then run the Web application and try to access files inside and outside of C:\Temp. The code access security policy that you configured in Step 4 constrains the code so that it is only allowed to access files from beneath C:\Temp.
The assembly should be installed in the GAC because of the ASP.NET loads strong named assemblies as domain neutral assemblies. All strong named assemblies that ASP.NET Web applications call should be installed in the GAC. For more information about this issue, see "Strong Names" in Chapter 7, "Building Secure Assemblies."
Note | Normally, default machine policy and ASP.NET policy grant full trust to assemblies that are installed in the GAC. The This policy level will only have the permissions from the permission set associated with this code group and Policy levels below this level will not be evaluated attributes that you assigned to the code group created in Step 4 ensure that the assembly is not granted full trust, and is only granted the permissions defined by the RestrictedFileIO permission set that you created earlier. |
Task To test file I/O with code access security constraints
Install the FileIO assembly into the GAC using the Gacutil.exe utility.
You can call Gacutil.exe as a post-build step to ensure that it is placed in the GAC when it has been successfully built inside Microsoft Visual Studio .NET.
Display the FileIO project's Properties dialog box in Visual Studio .NET.
In Common Properties , select Build Events .
Type " C:\Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1\Bin\gacutil" -i $(TargetPath) in the Post-build Event Command Line field.
Click OK to close the project Properties dialog box.
Rebuild the solution.
Run Iisreset.exe from a command line to force the ASP.NET process to be recycled.
This forces the permission grant for the FileIO assembly to be recomputed. If the ASP.NET application domain is still active from the last time you ran the Web application, the assembly could still be cached by ASP.NET.
Run the Web application, and then click Read File .
The contents of the text file should be successfully displayed. The policy that you created allows the FileIO assembly to read files from C:\Temp and below.
Enter C:\somefile.txt in the text box, and then click Read File .
A SecurityException should be generated because the code access security policy that you configured does not allow file I/O outside of the C:\Temp directory.
The exception details indicate that a request for the FileIOPermission has failed, as shown below:
System.Security.SecurityException: Request for the permission of type System.Security.Permissions.FileIOPermission, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 failed.