
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
1010
|
Chapter 17: Security
• A high surrogate value is not followed by a low surrogate value.
• In the case of the
GetBytes method, the byte[] that is used to hold the resulting
bytes is not large enough.
• In the case of the
GetChars method, the char[] that is used to hold the resulting
characters is not large enough.
If you use a constructor other than the one shown in this recipe or if you set the last
parameter in this constructor to
false, any errors in the encoding sequence are
ignored and no exception is thrown.
See Also
See the “UnicodeEncoding Class” and “UTF8Encoding Class” topic in the MSDN
documentation.
17.20 Obtaining a Safer File Handle
Problem
You want more security when manipulating an unmanaged file handle than a simple
IntPtr can provide.
Solution
Use the Microsoft.Win32.SafeHandles.SafeFileHandle object to wrap an existing
unmanaged file handle:
public static void WriteToFileHandle(IntPtr hFile)
{
// Wrap our file handle in a safe handle wrapper object.
using (Microsoft.Win32.SafeHandles.SafeFileHandle safeHFile =
new Microsoft.Win32.SafeHandles.SafeFileHandle(hFile, true))
{
// Open a FileStream object using the passed-in safe file handle.
using (FileStream fileStream = new FileStream(safeHFile,
FileAccess.ReadWrite))
{
// Flush before we start to clear any pending unmanaged ...