source: trunk/eraser6/Eraser.Util/KernelApi.cs @ 1675

Revision 1675, 54.6 KB checked in by lowjoel, 4 years ago (diff)

Updated copyright information: since Eraser is still under development we should update our copyright status.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
Line 
1/*
2 * $Id$
3 * Copyright 2008-2010 The Eraser Project
4 * Original Author: Joel Low <lowjoel@users.sourceforge.net>
5 * Modified By: Garrett Trant <gtrant@users.sourceforge.net>
6 *
7 * This file is part of Eraser.
8 *
9 * Eraser is free software: you can redistribute it and/or modify it under the
10 * terms of the GNU General Public License as published by the Free Software
11 * Foundation, either version 3 of the License, or (at your option) any later
12 * version.
13 *
14 * Eraser is distributed in the hope that it will be useful, but WITHOUT ANY
15 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
17 *
18 * A copy of the GNU General Public License can be found at
19 * <http://www.gnu.org/licenses/>.
20 */
21
22using System;
23using System.Collections.Generic;
24using System.Text;
25using System.Reflection;
26using System.Runtime.InteropServices;
27using Microsoft.Win32.SafeHandles;
28using System.ComponentModel;
29
30namespace Eraser.Util
31{
32    public static class KernelApi
33    {
34        /// <summary>
35        /// Allocates a new console for the calling process.
36        /// </summary>
37        /// <returns>If the function succeeds, the return value is nonzero.
38        ///
39        /// If the function fails, the return value is zero. To get extended error
40        /// information, call Marshal.GetLastWin32Error.</returns>
41        /// <remarks>A process can be associated with only one console, so the AllocConsole
42        /// function fails if the calling process already has a console. A process can
43        /// use the FreeConsole function to detach itself from its current console, then
44        /// it can call AllocConsole to create a new console or AttachConsole to attach
45        /// to another console.
46        ///
47        /// If the calling process creates a child process, the child inherits the
48        /// new console.
49        ///
50        /// AllocConsole initializes standard input, standard output, and standard error
51        /// handles for the new console. The standard input handle is a handle to the
52        /// console's input buffer, and the standard output and standard error handles
53        /// are handles to the console's screen buffer. To retrieve these handles, use
54        /// the GetStdHandle function.
55        ///
56        /// This function is primarily used by graphical user interface (GUI) application
57        /// to create a console window. GUI applications are initialized without a
58        /// console. Console applications are initialized with a console, unless they
59        /// are created as detached processes (by calling the CreateProcess function
60        /// with the DETACHED_PROCESS flag).</remarks>
61        public static bool AllocConsole()
62        {
63            return NativeMethods.AllocConsole();
64        }
65
66        /// <summary>
67        /// Detaches the calling process from its console.
68        /// </summary>
69        /// <returns>If the function succeeds, the return value is nonzero.
70        ///
71        /// If the function fails, the return value is zero. To get extended error
72        /// information, call Marshal.GetLastWin32Error.</returns>
73        /// <remarks>A process can be attached to at most one console. If the calling
74        /// process is not already attached to a console, the error code returned is
75        /// ERROR_INVALID_PARAMETER (87).
76        ///
77        /// A process can use the FreeConsole function to detach itself from its
78        /// console. If other processes share the console, the console is not destroyed,
79        /// but the process that called FreeConsole cannot refer to it. A console is
80        /// closed when the last process attached to it terminates or calls FreeConsole.
81        /// After a process calls FreeConsole, it can call the AllocConsole function to
82        /// create a new console or AttachConsole to attach to another console.</remarks>
83        public static bool FreeConsole()
84        {
85            return NativeMethods.FreeConsole();
86        }
87
88        private static DateTime FileTimeToDateTime(System.Runtime.InteropServices.ComTypes.FILETIME value)
89        {
90            long time = (long)((((ulong)value.dwHighDateTime) << sizeof(int) * 8) |
91                (uint)value.dwLowDateTime);
92            return DateTime.FromFileTime(time);
93        }
94
95        private static System.Runtime.InteropServices.ComTypes.FILETIME DateTimeToFileTime(DateTime value)
96        {
97            long time = value.ToFileTime();
98
99            System.Runtime.InteropServices.ComTypes.FILETIME result =
100                new System.Runtime.InteropServices.ComTypes.FILETIME();
101            result.dwLowDateTime = (int)(time & 0xFFFFFFFFL);
102            result.dwHighDateTime = (int)(time >> 32);
103
104            return result;
105        }
106
107        /// <summary>
108        /// Converts a Win32 Error code to a HRESULT.
109        /// </summary>
110        /// <param name="errorCode">The error code to convert.</param>
111        /// <returns>A HRESULT value representing the error code.</returns>
112        internal static int GetHRForWin32Error(int errorCode)
113        {
114            const uint FACILITY_WIN32 = 7;
115            return errorCode <= 0 ? errorCode :
116                (int)((((uint)errorCode) & 0x0000FFFF) | (FACILITY_WIN32 << 16) | 0x80000000);
117        }
118
119        /// <summary>
120        /// Gets a Exception for the given Win32 error code.
121        /// </summary>
122        /// <param name="errorCode">The error code.</param>
123        /// <returns>An exception object representing the error code.</returns>
124        internal static Exception GetExceptionForWin32Error(int errorCode)
125        {
126            int HR = GetHRForWin32Error(errorCode);
127            return Marshal.GetExceptionForHR(HR);
128        }
129
130        public static void GetFileTime(SafeFileHandle file, out DateTime creationTime,
131            out DateTime accessedTime, out DateTime modifiedTime)
132        {
133            System.Runtime.InteropServices.ComTypes.FILETIME accessedTimeNative =
134                new System.Runtime.InteropServices.ComTypes.FILETIME();
135            System.Runtime.InteropServices.ComTypes.FILETIME modifiedTimeNative =
136                new System.Runtime.InteropServices.ComTypes.FILETIME();
137            System.Runtime.InteropServices.ComTypes.FILETIME createdTimeNative =
138                new System.Runtime.InteropServices.ComTypes.FILETIME();
139
140            if (!NativeMethods.GetFileTime(file, out createdTimeNative, out accessedTimeNative,
141                out modifiedTimeNative))
142            {
143                throw GetExceptionForWin32Error(Marshal.GetLastWin32Error());
144            }
145
146            creationTime = FileTimeToDateTime(createdTimeNative);
147            accessedTime = FileTimeToDateTime(accessedTimeNative);
148            modifiedTime = FileTimeToDateTime(modifiedTimeNative);
149        }
150
151        public static void SetFileTime(SafeFileHandle file, DateTime creationTime,
152            DateTime accessedTime, DateTime modifiedTime)
153        {
154            System.Runtime.InteropServices.ComTypes.FILETIME accessedTimeNative =
155                new System.Runtime.InteropServices.ComTypes.FILETIME();
156            System.Runtime.InteropServices.ComTypes.FILETIME modifiedTimeNative =
157                new System.Runtime.InteropServices.ComTypes.FILETIME();
158            System.Runtime.InteropServices.ComTypes.FILETIME createdTimeNative =
159                new System.Runtime.InteropServices.ComTypes.FILETIME();
160
161            if (!NativeMethods.GetFileTime(file, out createdTimeNative,
162                out accessedTimeNative, out modifiedTimeNative))
163            {
164                throw KernelApi.GetExceptionForWin32Error(Marshal.GetLastWin32Error());
165            }
166
167            if (creationTime != DateTime.MinValue)
168                createdTimeNative = DateTimeToFileTime(creationTime);
169            if (accessedTime != DateTime.MinValue)
170                accessedTimeNative = DateTimeToFileTime(accessedTime);
171            if (modifiedTime != DateTime.MinValue)
172                modifiedTimeNative = DateTimeToFileTime(modifiedTime);
173
174            if (!NativeMethods.SetFileTime(file, ref createdTimeNative,
175                ref accessedTimeNative, ref modifiedTimeNative))
176            {
177                throw KernelApi.GetExceptionForWin32Error(Marshal.GetLastWin32Error());
178            }
179        }
180
181        /// <summary>
182        /// Retrieves the current value of the high-resolution performance counter.
183        /// </summary>
184        public static long PerformanceCounter
185        {
186            get
187            {
188                long result = 0;
189                if (NativeMethods.QueryPerformanceCounter(out result))
190                    return result;
191                return 0;
192            }
193        }
194
195        /// <summary>
196        /// Gets the current CPU type of the system.
197        /// </summary>
198        /// <returns>One of the <see cref="ProcessorTypes"/> enumeration values.</returns>
199        public static ProcessorArchitecture ProcessorArchitecture
200        {
201            get
202            {
203                NativeMethods.SYSTEM_INFO info = new NativeMethods.SYSTEM_INFO();
204                NativeMethods.GetSystemInfo(out info);
205
206                switch (info.processorArchitecture)
207                {
208                    case NativeMethods.SYSTEM_INFO.ProcessorArchitecture.PROCESSOR_ARCHITECTURE_AMD64:
209                        return ProcessorArchitecture.Amd64;
210                    case NativeMethods.SYSTEM_INFO.ProcessorArchitecture.PROCESSOR_ARCHITECTURE_IA64:
211                        return ProcessorArchitecture.IA64;
212                    case NativeMethods.SYSTEM_INFO.ProcessorArchitecture.PROCESSOR_ARCHITECTURE_INTEL:
213                        return ProcessorArchitecture.X86;
214                    default:
215                        return ProcessorArchitecture.None;
216                }
217            }
218        }
219
220        /// <summary>
221        /// Enables an application to inform the system that it is in use, thereby
222        /// preventing the system from entering sleep or turning off the display
223        /// while the application is running.
224        /// </summary>
225        /// <param name="executionState">The thread's execution requirements. This
226        /// parameter can be one or more of the EXECUTION_STATE values.</param>
227        /// <returns>If the function succeeds, the return value is the previous
228        /// thread execution state.
229        ///
230        /// If the function fails, the return value is NULL.</returns>
231        /// <remarks>The system automatically detects activities such as local keyboard
232        /// or mouse input, server activity, and changing window focus. Activities
233        /// that are not automatically detected include disk or CPU activity and
234        /// video display.
235        ///
236        /// Calling SetThreadExecutionState without ES_CONTINUOUS simply resets
237        /// the idle timer; to keep the display or system in the working state,
238        /// the thread must call SetThreadExecutionState periodically.
239        ///
240        /// To run properly on a power-managed computer, applications such as fax
241        /// servers, answering machines, backup agents, and network management
242        /// applications must use both ES_SYSTEM_REQUIRED and ES_CONTINUOUS when
243        /// they process events. Multimedia applications, such as video players
244        /// and presentation applications, must use ES_DISPLAY_REQUIRED when they
245        /// display video for long periods of time without user input. Applications
246        /// such as word processors, spreadsheets, browsers, and games do not need
247        /// to call SetThreadExecutionState.
248        ///
249        /// The ES_AWAYMODE_REQUIRED value should be used only when absolutely
250        /// necessary by media applications that require the system to perform
251        /// background tasks such as recording television content or streaming media
252        /// to other devices while the system appears to be sleeping. Applications
253        /// that do not require critical background processing or that run on
254        /// portable computers should not enable away mode because it prevents
255        /// the system from conserving power by entering true sleep.
256        ///
257        /// To enable away mode, an application uses both ES_AWAYMODE_REQUIRED and
258        /// ES_CONTINUOUS; to disable away mode, an application calls
259        /// SetThreadExecutionState with ES_CONTINUOUS and clears
260        /// ES_AWAYMODE_REQUIRED. When away mode is enabled, any operation that
261        /// would put the computer to sleep puts it in away mode instead. The computer
262        /// appears to be sleeping while the system continues to perform tasks that
263        /// do not require user input. Away mode does not affect the sleep idle
264        /// timer; to prevent the system from entering sleep when the timer expires,
265        /// an application must also set the ES_SYSTEM_REQUIRED value.
266        ///
267        /// The SetThreadExecutionState function cannot be used to prevent the user
268        /// from putting the computer to sleep. Applications should respect that
269        /// the user expects a certain behavior when they close the lid on their
270        /// laptop or press the power button.
271        ///
272        /// This function does not stop the screen saver from executing.
273        /// </remarks>
274        public static ThreadExecutionState SetThreadExecutionState(
275            ThreadExecutionState executionState)
276        {
277            return (ThreadExecutionState)NativeMethods.SetThreadExecutionState(
278                (NativeMethods.EXECUTION_STATE)executionState);
279        }
280
281        public class DiskPerformanceInfo
282        {
283            unsafe internal DiskPerformanceInfo(NativeMethods.DiskPerformanceInfoInternal info)
284            {
285                BytesRead = info.BytesRead;
286                BytesWritten = info.BytesWritten;
287                ReadTime = info.ReadTime;
288                WriteTime = info.WriteTime;
289                IdleTime = info.IdleTime;
290                ReadCount = info.ReadCount;
291                WriteCount = info.WriteCount;
292                QueueDepth = info.QueueDepth;
293                SplitCount = info.SplitCount;
294                QueryTime = info.QueryTime;
295                StorageDeviceNumber = info.StorageDeviceNumber;
296                StorageManagerName = new string((char*)info.StorageManagerName);
297            }
298
299            public long BytesRead { get; private set; }
300            public long BytesWritten { get; private set; }
301            public long ReadTime { get; private set; }
302            public long WriteTime { get; private set; }
303            public long IdleTime { get; private set; }
304            public uint ReadCount { get; private set; }
305            public uint WriteCount { get; private set; }
306            public uint QueueDepth { get; private set; }
307            public uint SplitCount { get; private set; }
308            public long QueryTime { get; private set; }
309            public uint StorageDeviceNumber { get; private set; }
310            public string StorageManagerName { get; private set; }
311        }
312
313        /// <summary>
314        /// Queries the performance information for the given disk.
315        /// </summary>
316        /// <param name="diskHandle">A read-only handle to a device (disk).</param>
317        /// <returns>A DiskPerformanceInfo structure describing the performance
318        /// information for the given disk.</returns>
319        public static DiskPerformanceInfo QueryDiskPerformanceInfo(SafeFileHandle diskHandle)
320        {
321            if (diskHandle.IsInvalid)
322                throw new ArgumentException("The disk handle must not be invalid.");
323
324            //This only works if the user has turned on the disk performance
325            //counters with 'diskperf -y'. These counters are off by default
326            NativeMethods.DiskPerformanceInfoInternal result =
327                new NativeMethods.DiskPerformanceInfoInternal();
328            uint bytesReturned = 0;
329            if (NativeMethods.DeviceIoControl(diskHandle, NativeMethods.IOCTL_DISK_PERFORMANCE,
330                IntPtr.Zero, 0, out result, (uint)Marshal.SizeOf(result), out bytesReturned, IntPtr.Zero))
331            {
332                return new DiskPerformanceInfo(result);
333            }
334
335            return null;
336        }
337
338        /// <summary>
339        /// Stores Kernel32.dll functions, structs and constants.
340        /// </summary>
341        internal static class NativeMethods
342        {
343            /// <summary>
344            /// Closes an open object handle.
345            /// </summary>
346            /// <param name="hObject">A valid handle to an open object.</param>
347            /// <returns>If the function succeeds, the return value is true. To get
348            /// extended error information, call Marshal.GetLastWin32Error().
349            ///
350            /// If the application is running under a debugger, the function will throw
351            /// an exception if it receives either a handle value that is not valid
352            /// or a pseudo-handle value. This can happen if you close a handle twice,
353            /// or if you call CloseHandle on a handle returned by the FindFirstFile
354            /// function.</returns>
355            [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
356            [return: MarshalAs(UnmanagedType.Bool)]
357            public static extern bool CloseHandle(IntPtr hObject);
358
359            /// <summary>
360            /// Deletes an existing file.
361            /// </summary>
362            /// <param name="lpFileName">The name of the file to be deleted.
363            ///
364            /// In the ANSI version of this function, the name is limited to MAX_PATH
365            /// characters. To extend this limit to 32,767 wide characters, call
366            /// the Unicode version of the function and prepend "\\?\" to the path.
367            /// For more information, see Naming a File.</param>
368            /// <returns>If the function succeeds, the return value is nonzero.
369            ///
370            /// If the function fails, the return value is zero (0). To get extended
371            /// error information, call Marshal.GetLastWin32Error().</returns>
372            [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
373            [return: MarshalAs(UnmanagedType.Bool)]
374            public static extern bool DeleteFile(string lpFileName);
375
376            /// <summary>
377            /// Retrieves a pseudo handle for the current process.
378            /// </summary>
379            /// <returns>A pseudo handle to the current process.</returns>
380            /// <remarks>A pseudo handle is a special constant, currently (HANDLE)-1,
381            /// that is interpreted as the current process handle. For compatibility
382            /// with future operating systems, it is best to call GetCurrentProcess
383            /// instead of hard-coding this constant value. The calling process can
384            /// use a pseudo handle to specify its own process whenever a process
385            /// handle is required. Pseudo handles are not inherited by child processes.
386            ///
387            /// This handle has the maximum possible access to the process object.
388            /// For systems that support security descriptors, this is the maximum
389            /// access allowed by the security descriptor for the calling process.
390            /// For systems that do not support security descriptors, this is
391            /// PROCESS_ALL_ACCESS. For more information, see Process Security and
392            /// Access Rights.
393            ///
394            /// A process can create a "real" handle to itself that is valid in the
395            /// context of other processes, or that can be inherited by other processes,
396            /// by specifying the pseudo handle as the source handle in a call to the
397            /// DuplicateHandle function. A process can also use the OpenProcess
398            /// function to open a real handle to itself.
399            ///
400            /// The pseudo handle need not be closed when it is no longer needed.
401            /// Calling the CloseHandle function with a pseudo handle has no effect.
402            /// If the pseudo handle is duplicated by DuplicateHandle, the duplicate
403            /// handle must be closed.</remarks>
404            [DllImport("Kernel32.dll", SetLastError = true)]
405            public static extern IntPtr GetCurrentProcess();
406
407            /// <summary>
408            /// Retrieves information about the current system.
409            /// </summary>
410            /// <param name="lpSystemInfo">A pointer to a SYSTEM_INFO structure that
411            /// receives the information.</param>
412            [DllImport("Kernel32.dll")]
413            public static extern void GetSystemInfo(out SYSTEM_INFO lpSystemInfo);
414
415            /// <summary>
416            /// The QueryPerformanceCounter function retrieves the current value of
417            /// the high-resolution performance counter.
418            /// </summary>
419            /// <param name="lpPerformanceCount">[out] Pointer to a variable that receives
420            /// the current performance-counter value, in counts.</param>
421            /// <returns>If the function succeeds, the return value is nonzero.
422            ///
423            /// If the function fails, the return value is zero. To get extended error
424            /// information, call Marshal.GetLastWin32Error. </returns>
425            [DllImport("Kernel32.dll", SetLastError = true)]
426            [return: MarshalAs(UnmanagedType.Bool)]
427            public static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
428
429            /// <summary>
430            /// Contains information about the current computer system. This includes
431            /// the architecture and type of the processor, the number of processors
432            /// in the system, the page size, and other such information.
433            /// </summary>
434            [StructLayout(LayoutKind.Sequential)]
435            internal struct SYSTEM_INFO
436            {
437                /// <summary>
438                /// Represents a list of processor architectures.
439                /// </summary>
440                public enum ProcessorArchitecture : ushort
441                {
442                    /// <summary>
443                    /// x64 (AMD or Intel).
444                    /// </summary>
445                    PROCESSOR_ARCHITECTURE_AMD64 = 9,
446
447                    /// <summary>
448                    /// Intel Itanium Processor Family (IPF).
449                    /// </summary>
450                    PROCESSOR_ARCHITECTURE_IA64 = 6,
451
452                    /// <summary>
453                    /// x86.
454                    /// </summary>
455                    PROCESSOR_ARCHITECTURE_INTEL = 0,
456
457                    /// <summary>
458                    /// Unknown architecture.
459                    /// </summary>
460                    PROCESSOR_ARCHITECTURE_UNKNOWN = 0xffff
461                }
462
463                /// <summary>
464                /// The processor architecture of the installed operating system.
465                /// This member can be one of the ProcessorArchitecture values.
466                /// </summary>
467                public ProcessorArchitecture processorArchitecture;
468
469                /// <summary>
470                /// This member is reserved for future use.
471                /// </summary>
472                private const ushort reserved = 0;
473
474                /// <summary>
475                /// The page size and the granularity of page protection and commitment.
476                /// This is the page size used by the VirtualAlloc function.
477                /// </summary>
478                public uint pageSize;
479
480                /// <summary>
481                /// A pointer to the lowest memory address accessible to applications
482                /// and dynamic-link libraries (DLLs).
483                /// </summary>
484                public IntPtr minimumApplicationAddress;
485
486                /// <summary>
487                /// A pointer to the highest memory address accessible to applications
488                /// and DLLs.
489                /// </summary>
490                public IntPtr maximumApplicationAddress;
491
492                /// <summary>
493                /// A mask representing the set of processors configured into the system.
494                /// Bit 0 is processor 0; bit 31 is processor 31.
495                /// </summary>
496                public IntPtr activeProcessorMask;
497
498                /// <summary>
499                /// The number of processors in the system.
500                /// </summary>
501                public uint numberOfProcessors;
502
503                /// <summary>
504                /// An obsolete member that is retained for compatibility. Use the
505                /// wProcessorArchitecture, wProcessorLevel, and wProcessorRevision
506                /// members to determine the type of processor.
507                /// Name                        Value
508                /// PROCESSOR_INTEL_386         386
509                /// PROCESSOR_INTEL_486         486
510                /// PROCESSOR_INTEL_PENTIUM     586
511                /// PROCESSOR_INTEL_IA64        2200
512                /// PROCESSOR_AMD_X8664         8664
513                /// </summary>
514                public uint processorType;
515
516                /// <summary>
517                /// The granularity for the starting address at which virtual memory
518                /// can be allocated. For more information, see VirtualAlloc.
519                /// </summary>
520                public uint allocationGranularity;
521
522                /// <summary>
523                /// The architecture-dependent processor level. It should be used only
524                /// for display purposes. To determine the feature set of a processor,
525                /// use the IsProcessorFeaturePresent function.
526                ///
527                /// If wProcessorArchitecture is PROCESSOR_ARCHITECTURE_INTEL, wProcessorLevel
528                /// is defined by the CPU vendor.
529                /// If wProcessorArchitecture is PROCESSOR_ARCHITECTURE_IA64, wProcessorLevel
530                /// is set to 1.
531                /// </summary>
532                public ushort processorLevel;
533
534                /// <summary>
535                /// The architecture-dependent processor revision. The following table
536                /// shows how the revision value is assembled for each type of
537                /// processor architecture.
538                ///
539                /// Processor                   Value
540                /// Intel Pentium, Cyrix        The high byte is the model and the
541                /// or NextGen 586              low byte is the stepping. For example,
542                ///                             if the value is xxyy, the model number
543                ///                             and stepping can be displayed as follows:
544                ///                             Model xx, Stepping yy
545                /// Intel 80386 or 80486        A value of the form xxyz.
546                ///                             If xx is equal to 0xFF, y - 0xA is the model
547                ///                             number, and z is the stepping identifier.
548                ///
549                ///                             If xx is not equal to 0xFF, xx + 'A'
550                ///                             is the stepping letter and yz is the minor stepping.
551                /// </summary>
552                public ushort processorRevision;
553            }
554
555            [DllImport("Kernel32.dll")]
556            public static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);
557
558            /// <summary>
559            /// Execution state values to be used in conjuction with SetThreadExecutionState
560            /// </summary>
561            [Flags]
562            public enum EXECUTION_STATE : uint
563            {
564                ES_AWAYMODE_REQUIRED = 0x00000040,
565                ES_CONTINUOUS = 0x80000000,
566                ES_DISPLAY_REQUIRED = 0x00000002,
567                ES_SYSTEM_REQUIRED = 0x00000001,
568                ES_USER_PRESENT = 0x00000004
569            }
570
571            [DllImport("Kernel32.dll", SetLastError = true)]
572            [return: MarshalAs(UnmanagedType.Bool)]
573            public static extern bool AllocConsole();
574
575            [DllImport("Kernel32.dll", SetLastError = true)]
576            [return: MarshalAs(UnmanagedType.Bool)]
577            public static extern bool FreeConsole();
578
579            /// <summary>
580            /// The CreateFile function creates or opens a file, file stream, directory,
581            /// physical disk, volume, console buffer, tape drive, communications resource,
582            /// mailslot, or named pipe. The function returns a handle that can be used
583            /// to access an object.
584            /// </summary>
585            /// <param name="FileName"></param>
586            /// <param name="DesiredAccess"> access to the object, which can be read,
587            /// write, or both</param>
588            /// <param name="ShareMode">The sharing mode of an object, which can be
589            /// read, write, both, or none</param>
590            /// <param name="SecurityAttributes">A pointer to a SECURITY_ATTRIBUTES
591            /// structure that determines whether or not the returned handle can be
592            /// inherited by child processes. Can be null</param>
593            /// <param name="CreationDisposition">An action to take on files that exist
594            /// and do not exist</param>
595            /// <param name="FlagsAndAttributes">The file attributes and flags.</param>
596            /// <param name="hTemplateFile">A handle to a template file with the
597            /// GENERIC_READ access right. The template file supplies file attributes
598            /// and extended attributes for the file that is being created. This
599            /// parameter can be null</param>
600            /// <returns>If the function succeeds, the return value is an open handle
601            /// to a specified file. If a specified file exists before the function
602            /// all and dwCreationDisposition is CREATE_ALWAYS or OPEN_ALWAYS, a call
603            /// to GetLastError returns ERROR_ALREADY_EXISTS, even when the function
604            /// succeeds. If a file does not exist before the call, GetLastError
605            /// returns 0.
606            ///
607            /// If the function fails, the return value is INVALID_HANDLE_VALUE.
608            /// To get extended error information, call Marshal.GetLastWin32Error().</returns>
609            [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
610            public static extern SafeFileHandle CreateFile(string lpFileName, uint dwDesiredAccess,
611                uint dwShareMode, IntPtr SecurityAttributes, uint dwCreationDisposition,
612                uint dwFlagsAndAttributes, IntPtr hTemplateFile);
613
614            public const uint GENERIC_READ = 0x80000000;
615            public const uint GENERIC_WRITE = 0x40000000;
616            public const uint GENERIC_EXECUTE = 0x20000000;
617            public const uint GENERIC_ALL = 0x10000000;
618
619            public const uint FILE_SHARE_READ = 0x00000001;
620            public const uint FILE_SHARE_WRITE = 0x00000002;
621            public const uint FILE_SHARE_DELETE = 0x00000004;
622
623            public const uint CREATE_NEW = 1;
624            public const uint CREATE_ALWAYS = 2;
625            public const uint OPEN_EXISTING = 3;
626            public const uint OPEN_ALWAYS = 4;
627            public const uint TRUNCATE_EXISTING = 5;
628
629            public const uint FILE_FLAG_WRITE_THROUGH = 0x80000000;
630            public const uint FILE_FLAG_OVERLAPPED = 0x40000000;
631            public const uint FILE_FLAG_NO_BUFFERING = 0x20000000;
632            public const uint FILE_FLAG_RANDOM_ACCESS = 0x10000000;
633            public const uint FILE_FLAG_SEQUENTIAL_SCAN = 0x08000000;
634            public const uint FILE_FLAG_DELETE_ON_CLOSE = 0x04000000;
635            public const uint FILE_FLAG_BACKUP_SEMANTICS = 0x02000000;
636            public const uint FILE_FLAG_POSIX_SEMANTICS = 0x01000000;
637            public const uint FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000;
638            public const uint FILE_FLAG_OPEN_NO_RECALL = 0x00100000;
639            public const uint FILE_FLAG_FIRST_PIPE_INSTANCE = 0x00080000;
640
641            [DllImport("Kernel32.dll", SetLastError = true)]
642            [return: MarshalAs(UnmanagedType.Bool)]
643            public extern static bool DeviceIoControl(SafeFileHandle hDevice,
644                uint dwIoControlCode, IntPtr lpInBuffer, uint nInBufferSize,
645                out ushort lpOutBuffer, uint nOutBufferSize, out uint lpBytesReturned,
646                IntPtr lpOverlapped);
647
648            [DllImport("Kernel32.dll", SetLastError = true)]
649            [return: MarshalAs(UnmanagedType.Bool)]
650            public extern static bool DeviceIoControl(SafeFileHandle hDevice,
651                uint dwIoControlCode, ref ushort lpInBuffer, uint nInBufferSize,
652                IntPtr lpOutBuffer, uint nOutBufferSize, out uint lpBytesReturned,
653                IntPtr lpOverlapped);
654
655            public const uint FSCTL_GET_COMPRESSION = 0x9003C;
656            public const uint FSCTL_SET_COMPRESSION = 0x9C040;
657            public const ushort COMPRESSION_FORMAT_NONE = 0x0000;
658            public const ushort COMPRESSION_FORMAT_DEFAULT = 0x0001;
659
660            [DllImport("Kernel32.dll", SetLastError = true)]
661            [return: MarshalAs(UnmanagedType.Bool)]
662            public extern static bool DeviceIoControl(SafeFileHandle hDevice,
663                uint dwIoControlCode, IntPtr lpInBuffer, uint nInBufferSize,
664                IntPtr lpOutBuffer, uint nOutBufferSize, out uint lpBytesReturned,
665                IntPtr lpOverlapped);
666            public const uint FSCTL_LOCK_VOLUME = 0x90018;
667            public const uint FSCTL_UNLOCK_VOLUME = 0x9001C;
668
669            [DllImport("Kernel32.dll", SetLastError = true)]
670            [return: MarshalAs(UnmanagedType.Bool)]
671            public extern static bool DeviceIoControl(SafeFileHandle hDevice,
672                uint dwIoControlCode, IntPtr lpInBuffer, uint nInBufferSize,
673                out DiskPerformanceInfoInternal lpOutBuffer, uint nOutBufferSize, out uint lpBytesReturned,
674                IntPtr lpOverlapped);
675
676            public const uint IOCTL_DISK_PERFORMANCE = ((0x00000007) << 16) | ((0x0008) << 2);
677
678            public unsafe struct DiskPerformanceInfoInternal
679            {
680                public long BytesRead;
681                public long BytesWritten;
682                public long ReadTime;
683                public long WriteTime;
684                public long IdleTime;
685                public uint ReadCount;
686                public uint WriteCount;
687                public uint QueueDepth;
688                public uint SplitCount;
689                public long QueryTime;
690                public uint StorageDeviceNumber;
691                public fixed short StorageManagerName[8];
692            }
693       
694            /// <summary>
695            /// Retrieves a set of FAT file system attributes for a specified file or
696            /// directory.
697            /// </summary>
698            /// <param name="lpFileName">The name of the file or directory.</param>
699            /// <returns>If the function succeeds, the return value contains the attributes
700            /// of the specified file or directory.
701            ///
702            /// If the function fails, the return value is INVALID_FILE_ATTRIBUTES.
703            /// To get extended error information, call Marshal.GetLastWin32Error.
704            ///
705            /// The attributes can be one or more of the FILE_ATTRIBUTE_* values.</returns>
706            [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
707            public static extern uint GetFileAttributes(string lpFileName);
708
709            /// <summary>
710            /// Sets the attributes for a file or directory.
711            /// </summary>
712            /// <param name="lpFileName">The name of the file whose attributes are
713            /// to be set.</param>
714            /// <param name="dwFileAttributes">The file attributes to set for the file.
715            /// This parameter can be one or more of the FILE_ATTRIBUTE_* values.
716            /// However, all other values override FILE_ATTRIBUTE_NORMAL.</param>
717            /// <returns>If the function succeeds, the return value is nonzero.
718            ///
719            /// If the function fails, the return value is zero. To get extended error
720            /// information, call Marshal.GetLastWin32Error.</returns>
721            [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2205:UseManagedEquivalentsOfWin32Api")]
722            [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
723            [return: MarshalAs(UnmanagedType.Bool)]
724            public static extern bool SetFileAttributes(string lpFileName,
725                uint dwFileAttributes);
726
727            /// <summary>
728            /// Retrieves the size of the specified file.
729            /// </summary>
730            /// <param name="hFile">A handle to the file. The handle must have been
731            /// created with either the GENERIC_READ or GENERIC_WRITE access right.
732            /// For more information, see File Security and Access Rights.</param>
733            /// <param name="lpFileSize">A reference to a long that receives the file
734            /// size, in bytes.</param>
735            /// <returns>If the function succeeds, the return value is nonzero.
736            ///
737            /// If the function fails, the return value is zero. To get extended error
738            /// information, call Marshal.GetLastWin32Error.</returns>
739            [DllImport("Kernel32.dll", SetLastError = true)]
740            [return: MarshalAs(UnmanagedType.Bool)]
741            public static extern bool GetFileSizeEx(SafeFileHandle hFile, out long lpFileSize);
742
743            /// <summary>
744            /// Retrieves the date and time that a file or directory was created, last
745            /// accessed, and last modified.
746            /// </summary>
747            /// <param name="hFile">A handle to the file or directory for which dates
748            /// and times are to be retrieved. The handle must have been created using
749            /// the CreateFile function with the GENERIC_READ access right. For more
750            /// information, see File Security and Access Rights.</param>
751            /// <param name="lpCreationTime">A pointer to a FILETIME structure to
752            /// receive the date and time the file or directory was created. This
753            /// parameter can be NULL if the application does not require this
754            /// information.</param>
755            /// <param name="lpLastAccessTime">A pointer to a FILETIME structure to
756            /// receive the date and time the file or directory was last accessed. The
757            /// last access time includes the last time the file or directory was
758            /// written to, read from, or, in the case of executable files, run. This
759            /// parameter can be NULL if the application does not require this
760            /// information.</param>
761            /// <param name="lpLastWriteTime">A pointer to a FILETIME structure to
762            /// receive the date and time the file or directory was last written to,
763            /// truncated, or overwritten (for example, with WriteFile or SetEndOfFile).
764            /// This date and time is not updated when file attributes or security
765            /// descriptors are changed. This parameter can be NULL if the application
766            /// does not require this information.</param>
767            /// <returns>If the function succeeds, the return value is nonzero.
768            ///
769            /// If the function fails, the return value is zero. To get extended error
770            /// information, call Marshal.GetLastWin32Error().</returns>
771            [DllImport("Kernel32.dll", SetLastError = true)]
772            [return: MarshalAs(UnmanagedType.Bool)]
773            public static extern bool GetFileTime(SafeFileHandle hFile,
774                out System.Runtime.InteropServices.ComTypes.FILETIME lpCreationTime,
775                out System.Runtime.InteropServices.ComTypes.FILETIME lpLastAccessTime,
776                out System.Runtime.InteropServices.ComTypes.FILETIME lpLastWriteTime);
777
778            /// <summary>
779            /// Sets the date and time that the specified file or directory was created,
780            /// last accessed, or last modified.
781            /// </summary>
782            /// <param name="hFile">A handle to the file or directory. The handle must
783            /// have been created using the CreateFile function with the
784            /// FILE_WRITE_ATTRIBUTES access right. For more information, see File
785            /// Security and Access Rights.</param>
786            /// <param name="lpCreationTime">A pointer to a FILETIME structure that
787            /// contains the new creation date and time for the file or directory.
788            /// This parameter can be NULL if the application does not need to change
789            /// this information.</param>
790            /// <param name="lpLastAccessTime">A pointer to a FILETIME structure that
791            /// contains the new last access date and time for the file or directory.
792            /// The last access time includes the last time the file or directory was
793            /// written to, read from, or (in the case of executable files) run. This
794            /// parameter can be NULL if the application does not need to change this
795            /// information.
796            ///
797            /// To preserve the existing last access time for a file even after accessing
798            /// a file, call SetFileTime immediately after opening the file handle
799            /// with this parameter's FILETIME structure members initialized to
800            /// 0xFFFFFFFF.</param>
801            /// <param name="lpLastWriteTime">A pointer to a FILETIME structure that
802            /// contains the new last modified date and time for the file or directory.
803            /// This parameter can be NULL if the application does not need to change
804            /// this information.</param>
805            /// <returns>If the function succeeds, the return value is nonzero.
806            ///
807            /// If the function fails, the return value is zero. To get extended error
808            /// information, call GetLastError.</returns>
809            [DllImport("Kernel32.dll", SetLastError = true)]
810            [return: MarshalAs(UnmanagedType.Bool)]
811            public static extern bool SetFileTime(SafeFileHandle hFile,
812                ref System.Runtime.InteropServices.ComTypes.FILETIME lpCreationTime,
813                ref System.Runtime.InteropServices.ComTypes.FILETIME lpLastAccessTime,
814                ref System.Runtime.InteropServices.ComTypes.FILETIME lpLastWriteTime);
815
816            /// <summary>
817            /// Retrieves the name of a volume on a computer. FindFirstVolume is used
818            /// to begin scanning the volumes of a computer.
819            /// </summary>
820            /// <param name="lpszVolumeName">A pointer to a buffer that receives a
821            /// null-terminated string that specifies the unique volume name of the
822            /// first volume found.</param>
823            /// <param name="cchBufferLength">The length of the buffer to receive the
824            /// name, in TCHARs.</param>
825            /// <returns>If the function succeeds, the return value is a search handle
826            /// used in a subsequent call to the FindNextVolume and FindVolumeClose
827            /// functions.
828            ///
829            /// If the function fails to find any volumes, the return value is the
830            /// INVALID_HANDLE_VALUE error code. To get extended error information,
831            /// call GetLastError.</returns>
832            [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
833            public static extern SafeFileHandle FindFirstVolume(StringBuilder lpszVolumeName,
834                uint cchBufferLength);
835
836            /// <summary>
837            /// Continues a volume search started by a call to the FindFirstVolume
838            /// function. FindNextVolume finds one volume per call.
839            /// </summary>
840            /// <param name="hFindVolume">The volume search handle returned by a previous
841            /// call to the FindFirstVolume function.</param>
842            /// <param name="lpszVolumeName">A pointer to a string that receives the
843            /// unique volume name found.</param>
844            /// <param name="cchBufferLength">The length of the buffer that receives
845            /// the name, in TCHARs.</param>
846            /// <returns>If the function succeeds, the return value is nonzero.
847            ///
848            /// If the function fails, the return value is zero. To get extended error
849            /// information, call GetLastError. If no matching files can be found, the
850            /// GetLastError function returns the ERROR_NO_MORE_FILES error code. In
851            /// that case, close the search with the FindVolumeClose function.</returns>
852            [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
853            [return: MarshalAs(UnmanagedType.Bool)]
854            public static extern bool FindNextVolume(SafeHandle hFindVolume,
855                StringBuilder lpszVolumeName, uint cchBufferLength);
856
857            /// <summary>
858            /// Closes the specified volume search handle. The FindFirstVolume and
859            /// FindNextVolume functions use this search handle to locate volumes.
860            /// </summary>
861            /// <param name="hFindVolume">The volume search handle to be closed. This
862            /// handle must have been previously opened by the FindFirstVolume function.</param>
863            /// <returns>If the function succeeds, the return value is nonzero.
864            ///
865            /// If the function fails, the return value is zero. To get extended error
866            /// information, call GetLastError.</returns>
867            [DllImport("Kernel32.dll", SetLastError = true)]
868            [return: MarshalAs(UnmanagedType.Bool)]
869            public static extern bool FindVolumeClose(SafeHandle hFindVolume);
870
871            /// <summary>
872            /// Retrieves the name of a volume mount point on the specified volume.
873            /// FindFirstVolumeMountPoint is used to begin scanning the volume mount
874            /// points on a volume.
875            /// </summary>
876            /// <param name="lpszRootPathName">The unique volume name of the volume
877            /// to scan for volume mount points. A trailing backslash is required.</param>
878            /// <param name="lpszVolumeMountPoint">A pointer to a buffer that receives
879            /// the name of the first volume mount point found.</param>
880            /// <param name="cchBufferLength">The length of the buffer that receives
881            /// the volume mount point name, in TCHARs.</param>
882            /// <returns>If the function succeeds, the return value is a search handle
883            /// used in a subsequent call to the FindNextVolumeMountPoint and
884            /// FindVolumeMountPointClose functions.
885            ///
886            /// If the function fails to find a volume mount point on the volume, the
887            /// return value is the INVALID_HANDLE_VALUE error code. To get extended
888            /// error information, call GetLastError.</returns>
889            [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
890            public static extern SafeFileHandle FindFirstVolumeMountPoint(
891                string lpszRootPathName, StringBuilder lpszVolumeMountPoint,
892                uint cchBufferLength);
893
894            /// <summary>
895            /// Continues a volume mount point search started by a call to the
896            /// FindFirstVolumeMountPoint function. FindNextVolumeMountPoint finds one
897            /// volume mount point per call.
898            /// </summary>
899            /// <param name="hFindVolumeMountPoint">A mount-point search handle returned
900            /// by a previous call to the FindFirstVolumeMountPoint function.</param>
901            /// <param name="lpszVolumeMountPoint">A pointer to a buffer that receives
902            /// the name of the volume mount point found.</param>
903            /// <param name="cchBufferLength">The length of the buffer that receives
904            /// the names, in TCHARs.</param>
905            /// <returns>If the function succeeds, the return value is nonzero.
906            ///
907            /// If the function fails, the return value is zero. To get extended error
908            /// information, call GetLastError. If no matching files can be found, the
909            /// GetLastError function returns the ERROR_NO_MORE_FILES error code. In
910            /// that case, close the search with the FindVolumeMountPointClose function.</returns>
911            [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
912            [return: MarshalAs(UnmanagedType.Bool)]
913            public static extern bool FindNextVolumeMountPoint(
914                SafeHandle hFindVolumeMountPoint, StringBuilder lpszVolumeMountPoint,
915                uint cchBufferLength);
916
917            /// <summary>
918            /// Closes the specified mount-point search handle. The FindFirstVolumeMountPoint
919            /// and FindNextVolumeMountPoint  functions use this search handle to locate
920            /// volume mount points on a specified volume.
921            /// </summary>
922            /// <param name="hFindVolumeMountPoint">The mount-point search handle to
923            /// be closed. This handle must have been previously opened by the
924            /// FindFirstVolumeMountPoint function.</param>
925            /// <returns>If the function succeeds, the return value is nonzero.
926            ///
927            /// If the function fails, the return value is zero. To get extended error
928            /// information, call GetLastError.</returns>
929            [DllImport("Kernel32.dll", SetLastError = true)]
930            [return: MarshalAs(UnmanagedType.Bool)]
931            public static extern bool FindVolumeMountPointClose(SafeHandle hFindVolumeMountPoint);
932
933            /// <summary>
934            /// Retrieves information about the specified disk, including the amount
935            /// of free space on the disk.
936            ///
937            /// The GetDiskFreeSpace function cannot report volume sizes that are
938            /// greater than 2 gigabytes (GB). To ensure that your application works
939            /// with large capacity hard drives, use the GetDiskFreeSpaceEx function.
940            /// </summary>
941            /// <param name="lpRootPathName">The root directory of the disk for which
942            /// information is to be returned. If this parameter is NULL, the function
943            /// uses the root of the current disk. If this parameter is a UNC name,
944            /// it must include a trailing backslash (for example, \\MyServer\MyShare\).
945            /// Furthermore, a drive specification must have a trailing backslash
946            /// (for example, C:\). The calling application must have FILE_LIST_DIRECTORY
947            /// access rights for this directory.</param>
948            /// <param name="lpSectorsPerCluster">A pointer to a variable that receives
949            /// the number of sectors per cluster.</param>
950            /// <param name="lpBytesPerSector">A pointer to a variable that receives
951            /// the number of bytes per sector.</param>
952            /// <param name="lpNumberOfFreeClusters">A pointer to a variable that
953            /// receives the total number of free clusters on the disk that are
954            /// available to the user who is associated with the calling thread.
955            ///
956            /// If per-user disk quotas are in use, this value may be less than the
957            /// total number of free clusters on the disk.</param>
958            /// <param name="lpTotalNumberOfClusters">A pointer to a variable that
959            /// receives the total number of clusters on the disk that are available
960            /// to the user who is associated with the calling thread.
961            ///
962            /// If per-user disk quotas are in use, this value may be less than the
963            /// total number of clusters on the disk.</param>
964            /// <returns>If the function succeeds, the return value is true. To get
965            /// extended error information, call Marshal.GetLastWin32Error().</returns>
966            [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
967            [return: MarshalAs(UnmanagedType.Bool)]
968            public static extern bool GetDiskFreeSpace(
969                string lpRootPathName, out UInt32 lpSectorsPerCluster, out UInt32 lpBytesPerSector,
970                out UInt32 lpNumberOfFreeClusters, out UInt32 lpTotalNumberOfClusters);
971
972
973            /// <summary>
974            /// Retrieves information about the amount of space that is available on
975            /// a disk volume, which is the total amount of space, the total amount
976            /// of free space, and the total amount of free space available to the
977            /// user that is associated with the calling thread.
978            /// </summary>
979            /// <param name="lpDirectoryName">A directory on the disk.
980            ///
981            /// If this parameter is NULL, the function uses the root of the current
982            /// disk.
983            ///
984            /// If this parameter is a UNC name, it must include a trailing backslash,
985            /// for example, "\\MyServer\MyShare\".
986            ///
987            /// This parameter does not have to specify the root directory on a disk.
988            /// The function accepts any directory on a disk.
989            ///
990            /// The calling application must have FILE_LIST_DIRECTORY access rights
991            /// for this directory.</param>
992            /// <param name="lpFreeBytesAvailable">A pointer to a variable that receives
993            /// the total number of free bytes on a disk that are available to the
994            /// user who is associated with the calling thread.
995            ///
996            /// This parameter can be NULL.
997            ///
998            /// If per-user quotas are being used, this value may be less than the
999            /// total number of free bytes on a disk.</param>
1000            /// <param name="lpTotalNumberOfBytes">A pointer to a variable that receives
1001            /// the total number of bytes on a disk that are available to the user who
1002            /// is associated with the calling thread.
1003            ///
1004            /// This parameter can be NULL.
1005            ///
1006            /// If per-user quotas are being used, this value may be less than the
1007            /// total number of bytes on a disk.
1008            ///
1009            /// To determine the total number of bytes on a disk or volume, use
1010            /// IOCTL_DISK_GET_LENGTH_INFO.</param>
1011            /// <param name="lpTotalNumberOfFreeBytes">A pointer to a variable that
1012            /// receives the total number of free bytes on a disk.
1013            ///
1014            /// This parameter can be NULL.</param>
1015            /// <returns>If the function succeeds, the return value is nonzero.
1016            ///
1017            /// If the function fails, the return value is zero (0). To get extended
1018            /// error information, call GetLastError.</returns>
1019            [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
1020            [return: MarshalAs(UnmanagedType.Bool)]
1021            public static extern bool GetDiskFreeSpaceEx(
1022                string lpDirectoryName,
1023                out UInt64 lpFreeBytesAvailable,
1024                out UInt64 lpTotalNumberOfBytes,
1025                out UInt64 lpTotalNumberOfFreeBytes);
1026
1027            /// <summary>
1028            /// Determines whether a disk drive is a removable, fixed, CD-ROM, RAM disk,
1029            /// or network drive.
1030            /// </summary>
1031            /// <param name="lpRootPathName">The root directory for the drive.
1032            ///
1033            /// A trailing backslash is required. If this parameter is NULL, the function
1034            /// uses the root of the current directory.</param>
1035            /// <returns>The return value specifies the type of drive, which can be
1036            /// one of the DriveInfo.DriveType values.</returns>
1037            [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
1038            public static extern uint GetDriveType(string lpRootPathName);
1039
1040            /// <summary>
1041            /// Retrieves information about the file system and volume associated with
1042            /// the specified root directory.
1043            ///
1044            /// To specify a handle when retrieving this information, use the
1045            /// GetVolumeInformationByHandleW function.
1046            ///
1047            /// To retrieve the current compression state of a file or directory, use
1048            /// FSCTL_GET_COMPRESSION.
1049            /// </summary>
1050            /// <param name="lpRootPathName">    A pointer to a string that contains
1051            /// the root directory of the volume to be described.
1052            ///
1053            /// If this parameter is NULL, the root of the current directory is used.
1054            /// A trailing backslash is required. For example, you specify
1055            /// \\MyServer\MyShare as "\\MyServer\MyShare\", or the C drive as "C:\".</param>
1056            /// <param name="lpVolumeNameBuffer">A pointer to a buffer that receives
1057            /// the name of a specified volume. The maximum buffer size is MAX_PATH+1.</param>
1058            /// <param name="nVolumeNameSize">The length of a volume name buffer, in
1059            /// TCHARs. The maximum buffer size is MAX_PATH+1.
1060            ///
1061            /// This parameter is ignored if the volume name buffer is not supplied.</param>
1062            /// <param name="lpVolumeSerialNumber">A pointer to a variable that receives
1063            /// the volume serial number.
1064            ///
1065            /// This parameter can be NULL if the serial number is not required.
1066            ///
1067            /// This function returns the volume serial number that the operating system
1068            /// assigns when a hard disk is formatted. To programmatically obtain the
1069            /// hard disk's serial number that the manufacturer assigns, use the
1070            /// Windows Management Instrumentation (WMI) Win32_PhysicalMedia property
1071            /// SerialNumber.</param>
1072            /// <param name="lpMaximumComponentLength">A pointer to a variable that
1073            /// receives the maximum length, in TCHARs, of a file name component that
1074            /// a specified file system supports.
1075            ///
1076            /// A file name component is the portion of a file name between backslashes.
1077            ///
1078            /// The value that is stored in the variable that *lpMaximumComponentLength
1079            /// points to is used to indicate that a specified file system supports
1080            /// long names. For example, for a FAT file system that supports long names,
1081            /// the function stores the value 255, rather than the previous 8.3 indicator.
1082            /// Long names can also be supported on systems that use the NTFS file system.</param>
1083            /// <param name="lpFileSystemFlags">A pointer to a variable that receives
1084            /// flags associated with the specified file system.
1085            ///
1086            /// This parameter can be one or more of the FS_FILE* flags. However,
1087            /// FS_FILE_COMPRESSION and FS_VOL_IS_COMPRESSED are mutually exclusive.</param>
1088            /// <param name="lpFileSystemNameBuffer">A pointer to a buffer that receives
1089            /// the name of the file system, for example, the FAT file system or the
1090            /// NTFS file system. The maximum buffer size is MAX_PATH+1.</param>
1091            /// <param name="nFileSystemNameSize">The length of the file system name
1092            /// buffer, in TCHARs. The maximum buffer size is MAX_PATH+1.
1093            ///
1094            /// This parameter is ignored if the file system name buffer is not supplied.</param>
1095            /// <returns>If all the requested information is retrieved, the return value
1096            /// is nonzero.
1097            ///
1098            ///
1099            /// If not all the requested information is retrieved, the return value is
1100            /// zero (0). To get extended error information, call GetLastError.</returns>
1101            [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
1102            [return: MarshalAs(UnmanagedType.Bool)]
1103            public static extern bool GetVolumeInformation(
1104                string lpRootPathName,
1105                StringBuilder lpVolumeNameBuffer,
1106                uint nVolumeNameSize,
1107                out uint lpVolumeSerialNumber,
1108                out uint lpMaximumComponentLength,
1109                out uint lpFileSystemFlags,
1110                StringBuilder lpFileSystemNameBuffer,
1111                uint nFileSystemNameSize);
1112
1113            /// <summary>
1114            /// Retrieves the unique volume name for the specified volume mount point or root directory.
1115            /// </summary>
1116            /// <param name="lpszVolumeMountPoint">The path of a volume mount point (with a trailing
1117            /// backslash, "\") or a drive letter indicating a root directory (in the
1118            /// form "D:\").</param>
1119            /// <param name="lpszVolumeName">A pointer to a string that receives the
1120            /// volume name. This name is a unique volume name of the form
1121            /// "\\?\Volume{GUID}\" where GUID is the GUID that identifies the volume.</param>
1122            /// <param name="cchBufferLength">The length of the output buffer, in TCHARs.
1123            /// A reasonable size for the buffer to accommodate the largest possible
1124            /// volume name is 50 characters.</param>
1125            /// <returns>If the function succeeds, the return value is nonzero.
1126            ///
1127            /// If the function fails, the return value is zero. To get extended
1128            /// error information, call GetLastError.</returns>
1129            [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
1130            [return: MarshalAs(UnmanagedType.Bool)]
1131            public static extern bool GetVolumeNameForVolumeMountPoint(
1132                string lpszVolumeMountPoint, StringBuilder lpszVolumeName,
1133                uint cchBufferLength);
1134
1135            /// <summary>
1136            /// Retrieves a list of path names for the specified volume name.
1137            /// </summary>
1138            /// <param name="lpszVolumeName">The volume name.</param>
1139            /// <param name="lpszVolumePathNames">A pointer to a buffer that receives
1140            /// the list of volume path names. The list is an array of null-terminated
1141            /// strings terminated by an additional NULL character. If the buffer is
1142            /// not large enough to hold the complete list, the buffer holds as much
1143            /// of the list as possible.</param>
1144            /// <param name="cchBufferLength">The length of the lpszVolumePathNames
1145            /// buffer, in TCHARs.</param>
1146            /// <param name="lpcchReturnLength">If the call is successful, this parameter
1147            /// is the number of TCHARs copied to the lpszVolumePathNames buffer. Otherwise,
1148            /// this parameter is the size of the buffer required to hold the complete
1149            /// list, in TCHARs.</param>
1150            /// <returns></returns>
1151            [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
1152            [return: MarshalAs(UnmanagedType.Bool)]
1153            public static extern bool GetVolumePathNamesForVolumeName(
1154                string lpszVolumeName, IntPtr lpszVolumePathNames, uint cchBufferLength,
1155                out uint lpcchReturnLength);
1156
1157            public const int MaxPath = 260;
1158            public const int LongPath = 32768;
1159        }
1160    }
1161
1162    public enum ThreadExecutionState
1163    {
1164        /// <summary>
1165        /// No specific state
1166        /// </summary>
1167        None = 0,
1168
1169        /// <summary>
1170        /// Enables away mode. This value must be specified with ES_CONTINUOUS.
1171        ///
1172        /// Away mode should be used only by media-recording and media-distribution
1173        /// applications that must perform critical background processing on
1174        /// desktop computers while the computer appears to be sleeping.
1175        /// See remarks.
1176        ///
1177        /// Windows Server 2003 and Windows XP/2000: ES_AWAYMODE_REQUIRED is
1178        /// not supported.
1179        /// </summary>
1180        AwayModeRequired = (int)KernelApi.NativeMethods.EXECUTION_STATE.ES_AWAYMODE_REQUIRED,
1181
1182        /// <summary>
1183        /// Informs the system that the state being set should remain in effect
1184        /// until the next call that uses ES_CONTINUOUS and one of the other
1185        /// state flags is cleared.
1186        /// </summary>
1187        Continuous = unchecked((int)KernelApi.NativeMethods.EXECUTION_STATE.ES_CONTINUOUS),
1188
1189        /// <summary>
1190        /// Forces the display to be on by resetting the display idle timer.
1191        /// </summary>
1192        DisplayRequired = (int)KernelApi.NativeMethods.EXECUTION_STATE.ES_DISPLAY_REQUIRED,
1193
1194        /// <summary>
1195        /// Forces the system to be in the working state by resetting the system
1196        /// idle timer.
1197        /// </summary>
1198        SystemRequired = (int)KernelApi.NativeMethods.EXECUTION_STATE.ES_SYSTEM_REQUIRED,
1199
1200        /// <summary>
1201        /// This value is not supported. If ES_USER_PRESENT is combined with
1202        /// other esFlags values, the call will fail and none of the specified
1203        /// states will be set.
1204        ///
1205        /// Windows Server 2003 and Windows XP/2000: Informs the system that a
1206        /// user is present and resets the display and system idle timers.
1207        /// ES_USER_PRESENT must be called with ES_CONTINUOUS.
1208        /// </summary>
1209        UserPresent = (int)KernelApi.NativeMethods.EXECUTION_STATE.ES_USER_PRESENT
1210    }
1211}
Note: See TracBrowser for help on using the repository browser.