Information Technology Reference
In-Depth Information
pointers to access either the managed or unmanaged heaps. Whether you
knew it or not, almost all the C# code that you create is safe. Unless you
turn on the /unsafe C# compiler option, you've created verifiably safe
code. /unsafe allows the use of pointers, which the CLR cannot verify.
The reasons to use unsafe code are few, with the most common being per-
formance. Pointers to raw memory are faster than safe reference checks. In
a typical array, they can be up to ten times faster. But when you use unsafe
constructs, understand that unsafe code anywhere in an assembly affects
the entire assembly. When you create unsafe code blocks, consider isolat-
ing those algorithms in their own assembly (see Item 50). This limits the
effect that unsafe code has on your entire application. If it's isolated, only
callers who need the particular feature are affected. You can still use the
remaining safe functionality in more restrictive environments. You might
also need unsafe code to deal with P/Invoke or COM interfaces that require
raw pointers. The same recommendation applies: Isolate it. Unsafe code
should affect its own small assembly and nothing else.
The advice for memory access is simple: Avoid accessing unmanaged
memory whenever possible. When you do need to access unmanaged
memory, you should isolate that access in a separate assembly.
The next most common security concern is the file system. Programs store
data, often in files. Code that has been downloaded from the Internet does
not have access to most locations on the file system—that would be a huge
security hole. Yet, not accessing the file system at all would make it far more
difficult to create usable programs. This problem is solved by using iso-
lated storage. Isolated storage can be thought of as a virtual directory that
is isolated based on the assembly, the application domain, and the current
user. Optionally, you can use a more general isolated storage virtual direc-
tory that is based on the assembly and the current user.
Partially trusted assemblies can access their own specific isolated storage
area but nowhere else on the file system. The isolated storage directory is
hidden from other assemblies and other users. You use isolated storage
through the classes in the System.IO.IsolatedStorage namespace. The Iso-
latedStorageFile class contains methods very similar to the System.IO.File
class. In fact, it is derived from the System.IO.FileStream class. The code to
write to isolated storage is almost the same as writing to any file:
IsolatedStorageFile iso =
IsolatedStorageFile .GetUserStoreForDomain();
 
Search WWH ::




Custom Search