source: trunk/eraser6/Eraser.Util/NativeMethods/Kernel.cs @ 1874

Revision 1874, 42.1 KB checked in by lowjoel, 5 years ago (diff)

Add the current working directory, Operating system (including Vista/7 edition and service pack), CPU count and running processes to the debug report.

  • 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:
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.Runtime.InteropServices;
26using Microsoft.Win32.SafeHandles;
27
28namespace Eraser.Util
29{
30    /// <summary>
31    /// Stores Kernel32.dll functions, structs and constants.
32    /// </summary>
33    internal static partial class NativeMethods
34    {
35        /// <summary>
36        /// Deletes an existing file.
37        /// </summary>
38        /// <param name="lpFileName">The name of the file to be deleted.
39        ///
40        /// In the ANSI version of this function, the name is limited to MAX_PATH
41        /// characters. To extend this limit to 32,767 wide characters, call
42        /// the Unicode version of the function and prepend "\\?\" to the path.
43        /// For more information, see Naming a File.</param>
44        /// <returns>If the function succeeds, the return value is nonzero.
45        ///
46        /// If the function fails, the return value is zero (0). To get extended
47        /// error information, call Marshal.GetLastWin32Error().</returns>
48        [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
49        [return: MarshalAs(UnmanagedType.Bool)]
50        public static extern bool DeleteFile(string lpFileName);
51
52        /// <summary>
53        /// Retrieves information about the current system.
54        /// </summary>
55        /// <param name="lpSystemInfo">A pointer to a SYSTEM_INFO structure that
56        /// receives the information.</param>
57        [DllImport("Kernel32.dll")]
58        public static extern void GetSystemInfo(out SYSTEM_INFO lpSystemInfo);
59
60        /// <summary>
61        /// The QueryPerformanceCounter function retrieves the current value of
62        /// the high-resolution performance counter.
63        /// </summary>
64        /// <param name="lpPerformanceCount">[out] Pointer to a variable that receives
65        /// the current performance-counter value, in counts.</param>
66        /// <returns>If the function succeeds, the return value is nonzero.
67        ///
68        /// If the function fails, the return value is zero. To get extended error
69        /// information, call Marshal.GetLastWin32Error. </returns>
70        [DllImport("Kernel32.dll", SetLastError = true)]
71        [return: MarshalAs(UnmanagedType.Bool)]
72        public static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
73
74        /// <summary>
75        /// Contains information about the current computer system. This includes
76        /// the architecture and type of the processor, the number of processors
77        /// in the system, the page size, and other such information.
78        /// </summary>
79        [StructLayout(LayoutKind.Sequential)]
80        internal struct SYSTEM_INFO
81        {
82            /// <summary>
83            /// Represents a list of processor architectures.
84            /// </summary>
85            public enum ProcessorArchitecture : ushort
86            {
87                /// <summary>
88                /// x64 (AMD or Intel).
89                /// </summary>
90                PROCESSOR_ARCHITECTURE_AMD64 = 9,
91
92                /// <summary>
93                /// Intel Itanium Processor Family (IPF).
94                /// </summary>
95                PROCESSOR_ARCHITECTURE_IA64 = 6,
96
97                /// <summary>
98                /// x86.
99                /// </summary>
100                PROCESSOR_ARCHITECTURE_INTEL = 0,
101
102                /// <summary>
103                /// Unknown architecture.
104                /// </summary>
105                PROCESSOR_ARCHITECTURE_UNKNOWN = 0xffff
106            }
107
108            /// <summary>
109            /// The processor architecture of the installed operating system.
110            /// This member can be one of the ProcessorArchitecture values.
111            /// </summary>
112            public ProcessorArchitecture processorArchitecture;
113
114            /// <summary>
115            /// This member is reserved for future use.
116            /// </summary>
117            private const ushort reserved = 0;
118
119            /// <summary>
120            /// The page size and the granularity of page protection and commitment.
121            /// This is the page size used by the VirtualAlloc function.
122            /// </summary>
123            public uint pageSize;
124
125            /// <summary>
126            /// A pointer to the lowest memory address accessible to applications
127            /// and dynamic-link libraries (DLLs).
128            /// </summary>
129            public IntPtr minimumApplicationAddress;
130
131            /// <summary>
132            /// A pointer to the highest memory address accessible to applications
133            /// and DLLs.
134            /// </summary>
135            public IntPtr maximumApplicationAddress;
136
137            /// <summary>
138            /// A mask representing the set of processors configured into the system.
139            /// Bit 0 is processor 0; bit 31 is processor 31.
140            /// </summary>
141            public IntPtr activeProcessorMask;
142
143            /// <summary>
144            /// The number of processors in the system.
145            /// </summary>
146            public uint numberOfProcessors;
147
148            /// <summary>
149            /// An obsolete member that is retained for compatibility. Use the
150            /// wProcessorArchitecture, wProcessorLevel, and wProcessorRevision
151            /// members to determine the type of processor.
152            /// Name                        Value
153            /// PROCESSOR_INTEL_386         386
154            /// PROCESSOR_INTEL_486         486
155            /// PROCESSOR_INTEL_PENTIUM     586
156            /// PROCESSOR_INTEL_IA64        2200
157            /// PROCESSOR_AMD_X8664         8664
158            /// </summary>
159            public uint processorType;
160
161            /// <summary>
162            /// The granularity for the starting address at which virtual memory
163            /// can be allocated. For more information, see VirtualAlloc.
164            /// </summary>
165            public uint allocationGranularity;
166
167            /// <summary>
168            /// The architecture-dependent processor level. It should be used only
169            /// for display purposes. To determine the feature set of a processor,
170            /// use the IsProcessorFeaturePresent function.
171            ///
172            /// If wProcessorArchitecture is PROCESSOR_ARCHITECTURE_INTEL, wProcessorLevel
173            /// is defined by the CPU vendor.
174            /// If wProcessorArchitecture is PROCESSOR_ARCHITECTURE_IA64, wProcessorLevel
175            /// is set to 1.
176            /// </summary>
177            public ushort processorLevel;
178
179            /// <summary>
180            /// The architecture-dependent processor revision. The following table
181            /// shows how the revision value is assembled for each type of
182            /// processor architecture.
183            ///
184            /// Processor                   Value
185            /// Intel Pentium, Cyrix        The high byte is the model and the
186            /// or NextGen 586              low byte is the stepping. For example,
187            ///                             if the value is xxyy, the model number
188            ///                             and stepping can be displayed as follows:
189            ///                             Model xx, Stepping yy
190            /// Intel 80386 or 80486        A value of the form xxyz.
191            ///                             If xx is equal to 0xFF, y - 0xA is the model
192            ///                             number, and z is the stepping identifier.
193            ///
194            ///                             If xx is not equal to 0xFF, xx + 'A'
195            ///                             is the stepping letter and yz is the minor stepping.
196            /// </summary>
197            public ushort processorRevision;
198        }
199
200        [DllImport("Kernel32.dll")]
201        public static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);
202
203        [Flags]
204        public enum EXECUTION_STATE : uint
205        {
206            ES_AWAYMODE_REQUIRED = 0x00000040,
207            ES_CONTINUOUS = 0x80000000,
208            ES_DISPLAY_REQUIRED = 0x00000002,
209            ES_SYSTEM_REQUIRED = 0x00000001,
210            ES_USER_PRESENT = 0x00000004
211        }
212
213        /// <summary>
214        /// Allocates a new console for the calling process.
215        /// </summary>
216        /// <returns>If the function succeeds, the return value is nonzero.
217        ///
218        /// If the function fails, the return value is zero. To get extended error
219        /// information, call Marshal.GetLastWin32Error.</returns>
220        /// <remarks>A process can be associated with only one console, so the AllocConsole
221        /// function fails if the calling process already has a console. A process can
222        /// use the FreeConsole function to detach itself from its current console, then
223        /// it can call AllocConsole to create a new console or AttachConsole to attach
224        /// to another console.
225        ///
226        /// If the calling process creates a child process, the child inherits the
227        /// new console.
228        ///
229        /// AllocConsole initializes standard input, standard output, and standard error
230        /// handles for the new console. The standard input handle is a handle to the
231        /// console's input buffer, and the standard output and standard error handles
232        /// are handles to the console's screen buffer. To retrieve these handles, use
233        /// the GetStdHandle function.
234        ///
235        /// This function is primarily used by graphical user interface (GUI) application
236        /// to create a console window. GUI applications are initialized without a
237        /// console. Console applications are initialized with a console, unless they
238        /// are created as detached processes (by calling the CreateProcess function
239        /// with the DETACHED_PROCESS flag).</remarks>
240        [DllImport("Kernel32.dll", SetLastError = true)]
241        [return: MarshalAs(UnmanagedType.Bool)]
242        public static extern bool AllocConsole();
243
244        /// <summary>
245        /// Detaches the calling process from its console.
246        /// </summary>
247        /// <returns>If the function succeeds, the return value is nonzero.
248        ///
249        /// If the function fails, the return value is zero. To get extended error
250        /// information, call Marshal.GetLastWin32Error.</returns>
251        /// <remarks>A process can be attached to at most one console. If the calling
252        /// process is not already attached to a console, the error code returned is
253        /// ERROR_INVALID_PARAMETER (87).
254        ///
255        /// A process can use the FreeConsole function to detach itself from its
256        /// console. If other processes share the console, the console is not destroyed,
257        /// but the process that called FreeConsole cannot refer to it. A console is
258        /// closed when the last process attached to it terminates or calls FreeConsole.
259        /// After a process calls FreeConsole, it can call the AllocConsole function to
260        /// create a new console or AttachConsole to attach to another console.</remarks>
261        [DllImport("Kernel32.dll", SetLastError = true)]
262        [return: MarshalAs(UnmanagedType.Bool)]
263        public static extern bool FreeConsole();
264
265        /// <summary>
266        /// The CreateFile function creates or opens a file, file stream, directory,
267        /// physical disk, volume, console buffer, tape drive, communications resource,
268        /// mailslot, or named pipe. The function returns a handle that can be used
269        /// to access an object.
270        /// </summary>
271        /// <param name="FileName"></param>
272        /// <param name="DesiredAccess"> access to the object, which can be read,
273        /// write, or both</param>
274        /// <param name="ShareMode">The sharing mode of an object, which can be
275        /// read, write, both, or none</param>
276        /// <param name="SecurityAttributes">A pointer to a SECURITY_ATTRIBUTES
277        /// structure that determines whether or not the returned handle can be
278        /// inherited by child processes. Can be null</param>
279        /// <param name="CreationDisposition">An action to take on files that exist
280        /// and do not exist</param>
281        /// <param name="FlagsAndAttributes">The file attributes and flags.</param>
282        /// <param name="hTemplateFile">A handle to a template file with the
283        /// GENERIC_READ access right. The template file supplies file attributes
284        /// and extended attributes for the file that is being created. This
285        /// parameter can be null</param>
286        /// <returns>If the function succeeds, the return value is an open handle
287        /// to a specified file. If a specified file exists before the function
288        /// all and dwCreationDisposition is CREATE_ALWAYS or OPEN_ALWAYS, a call
289        /// to GetLastError returns ERROR_ALREADY_EXISTS, even when the function
290        /// succeeds. If a file does not exist before the call, GetLastError
291        /// returns 0.
292        ///
293        /// If the function fails, the return value is INVALID_HANDLE_VALUE.
294        /// To get extended error information, call Marshal.GetLastWin32Error().</returns>
295        [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
296        public static extern SafeFileHandle CreateFile(string lpFileName, uint dwDesiredAccess,
297            uint dwShareMode, IntPtr SecurityAttributes, uint dwCreationDisposition,
298            uint dwFlagsAndAttributes, IntPtr hTemplateFile);
299
300        public const uint FILE_READ_ATTRIBUTES = 0x0080;
301        public const uint GENERIC_READ = 0x80000000;
302        public const uint GENERIC_WRITE = 0x40000000;
303        public const uint GENERIC_EXECUTE = 0x20000000;
304        public const uint GENERIC_ALL = 0x10000000;
305
306        public const uint FILE_SHARE_READ = 0x00000001;
307        public const uint FILE_SHARE_WRITE = 0x00000002;
308        public const uint FILE_SHARE_DELETE = 0x00000004;
309
310        public const uint CREATE_NEW = 1;
311        public const uint CREATE_ALWAYS = 2;
312        public const uint OPEN_EXISTING = 3;
313        public const uint OPEN_ALWAYS = 4;
314        public const uint TRUNCATE_EXISTING = 5;
315
316        public const uint FILE_FLAG_WRITE_THROUGH = 0x80000000;
317        public const uint FILE_FLAG_OVERLAPPED = 0x40000000;
318        public const uint FILE_FLAG_NO_BUFFERING = 0x20000000;
319        public const uint FILE_FLAG_RANDOM_ACCESS = 0x10000000;
320        public const uint FILE_FLAG_SEQUENTIAL_SCAN = 0x08000000;
321        public const uint FILE_FLAG_DELETE_ON_CLOSE = 0x04000000;
322        public const uint FILE_FLAG_BACKUP_SEMANTICS = 0x02000000;
323        public const uint FILE_FLAG_POSIX_SEMANTICS = 0x01000000;
324        public const uint FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000;
325        public const uint FILE_FLAG_OPEN_NO_RECALL = 0x00100000;
326        public const uint FILE_FLAG_FIRST_PIPE_INSTANCE = 0x00080000;
327
328        [DllImport("Kernel32.dll", SetLastError = true)]
329        [return: MarshalAs(UnmanagedType.Bool)]
330        public extern static bool DeviceIoControl(SafeFileHandle hDevice,
331            uint dwIoControlCode, IntPtr lpInBuffer, uint nInBufferSize,
332            out ushort lpOutBuffer, uint nOutBufferSize, out uint lpBytesReturned,
333            IntPtr lpOverlapped);
334
335        [DllImport("Kernel32.dll", SetLastError = true)]
336        [return: MarshalAs(UnmanagedType.Bool)]
337        public extern static bool DeviceIoControl(SafeFileHandle hDevice,
338            uint dwIoControlCode, ref ushort lpInBuffer, uint nInBufferSize,
339            IntPtr lpOutBuffer, uint nOutBufferSize, out uint lpBytesReturned,
340            IntPtr lpOverlapped);
341
342        public const uint FSCTL_GET_COMPRESSION = 0x9003C;
343        public const uint FSCTL_SET_COMPRESSION = 0x9C040;
344        public const ushort COMPRESSION_FORMAT_NONE = 0x0000;
345        public const ushort COMPRESSION_FORMAT_DEFAULT = 0x0001;
346
347        [DllImport("Kernel32.dll", SetLastError = true)]
348        [return: MarshalAs(UnmanagedType.Bool)]
349        public extern static bool DeviceIoControl(SafeFileHandle hDevice,
350            uint dwIoControlCode, IntPtr lpInBuffer, uint nInBufferSize,
351            IntPtr lpOutBuffer, uint nOutBufferSize, out uint lpBytesReturned,
352            IntPtr lpOverlapped);
353
354        public const uint FSCTL_LOCK_VOLUME = 0x90018;
355        public const uint FSCTL_UNLOCK_VOLUME = 0x9001C;
356
357        [DllImport("Kernel32.dll", SetLastError = true)]
358        [return: MarshalAs(UnmanagedType.Bool)]
359        public extern static bool DeviceIoControl(SafeFileHandle hDevice,
360            uint dwIoControlCode, IntPtr lpInBuffer, uint nInBufferSize,
361            out DiskPerformanceInfoInternal lpOutBuffer, uint nOutBufferSize,
362            out uint lpBytesReturned, IntPtr lpOverlapped);
363
364        public const uint IOCTL_DISK_PERFORMANCE = ((0x00000007) << 16) | ((0x0008) << 2);
365
366        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
367        public struct DiskPerformanceInfoInternal
368        {
369            public long BytesRead;
370            public long BytesWritten;
371            public long ReadTime;
372            public long WriteTime;
373            public long IdleTime;
374            public uint ReadCount;
375            public uint WriteCount;
376            public uint QueueDepth;
377            public uint SplitCount;
378            public long QueryTime;
379            public uint StorageDeviceNumber;
380
381            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
382            public string StorageManagerName;
383        }
384
385        [DllImport("Kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
386        [return: MarshalAs(UnmanagedType.Bool)]
387        public static extern bool DeviceIoControl(SafeFileHandle hDevice,
388            uint dwIoControlCode, IntPtr lpInBuffer, uint nInBufferSize,
389            out NTFS_VOLUME_DATA_BUFFER lpOutBuffer, uint nOutBufferSize,
390            out uint lpBytesReturned, IntPtr lpOverlapped);
391
392        /// <summary>
393        /// Retrieves information about the specified NTFS file system volume.
394        /// </summary>
395        public const int FSCTL_GET_NTFS_VOLUME_DATA = (9 << 16) | (25 << 2);
396
397        /// <summary>
398        /// Retrieves a set of FAT file system attributes for a specified file or
399        /// directory.
400        /// </summary>
401        /// <param name="lpFileName">The name of the file or directory.</param>
402        /// <returns>If the function succeeds, the return value contains the attributes
403        /// of the specified file or directory.
404        ///
405        /// If the function fails, the return value is INVALID_FILE_ATTRIBUTES.
406        /// To get extended error information, call Marshal.GetLastWin32Error.
407        ///
408        /// The attributes can be one or more of the FILE_ATTRIBUTE_* values.</returns>
409        [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
410        public static extern uint GetFileAttributes(string lpFileName);
411
412        /// <summary>
413        /// Sets the attributes for a file or directory.
414        /// </summary>
415        /// <param name="lpFileName">The name of the file whose attributes are
416        /// to be set.</param>
417        /// <param name="dwFileAttributes">The file attributes to set for the file.
418        /// This parameter can be one or more of the FILE_ATTRIBUTE_* values.
419        /// However, all other values override FILE_ATTRIBUTE_NORMAL.</param>
420        /// <returns>If the function succeeds, the return value is nonzero.
421        ///
422        /// If the function fails, the return value is zero. To get extended error
423        /// information, call Marshal.GetLastWin32Error.</returns>
424        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2205:UseManagedEquivalentsOfWin32Api")]
425        [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
426        [return: MarshalAs(UnmanagedType.Bool)]
427        public static extern bool SetFileAttributes(string lpFileName,
428            uint dwFileAttributes);
429
430        /// <summary>
431        /// Retrieves the size of the specified file.
432        /// </summary>
433        /// <param name="hFile">A handle to the file. The handle must have been
434        /// created with either the GENERIC_READ or GENERIC_WRITE access right.
435        /// For more information, see File Security and Access Rights.</param>
436        /// <param name="lpFileSize">A reference to a long that receives the file
437        /// size, in bytes.</param>
438        /// <returns>If the function succeeds, the return value is nonzero.
439        ///
440        /// If the function fails, the return value is zero. To get extended error
441        /// information, call Marshal.GetLastWin32Error.</returns>
442        [DllImport("Kernel32.dll", SetLastError = true)]
443        [return: MarshalAs(UnmanagedType.Bool)]
444        public static extern bool GetFileSizeEx(SafeFileHandle hFile, out long lpFileSize);
445
446        /// <summary>
447        /// Retrieves the date and time that a file or directory was created, last
448        /// accessed, and last modified.
449        /// </summary>
450        /// <param name="hFile">A handle to the file or directory for which dates
451        /// and times are to be retrieved. The handle must have been created using
452        /// the CreateFile function with the GENERIC_READ access right. For more
453        /// information, see File Security and Access Rights.</param>
454        /// <param name="lpCreationTime">A pointer to a FILETIME structure to
455        /// receive the date and time the file or directory was created. This
456        /// parameter can be NULL if the application does not require this
457        /// information.</param>
458        /// <param name="lpLastAccessTime">A pointer to a FILETIME structure to
459        /// receive the date and time the file or directory was last accessed. The
460        /// last access time includes the last time the file or directory was
461        /// written to, read from, or, in the case of executable files, run. This
462        /// parameter can be NULL if the application does not require this
463        /// information.</param>
464        /// <param name="lpLastWriteTime">A pointer to a FILETIME structure to
465        /// receive the date and time the file or directory was last written to,
466        /// truncated, or overwritten (for example, with WriteFile or SetEndOfFile).
467        /// This date and time is not updated when file attributes or security
468        /// descriptors are changed. This parameter can be NULL if the application
469        /// does not require this information.</param>
470        /// <returns>If the function succeeds, the return value is nonzero.
471        ///
472        /// If the function fails, the return value is zero. To get extended error
473        /// information, call Marshal.GetLastWin32Error().</returns>
474        [DllImport("Kernel32.dll", SetLastError = true)]
475        [return: MarshalAs(UnmanagedType.Bool)]
476        public static extern bool GetFileTime(SafeFileHandle hFile,
477            out System.Runtime.InteropServices.ComTypes.FILETIME lpCreationTime,
478            out System.Runtime.InteropServices.ComTypes.FILETIME lpLastAccessTime,
479            out System.Runtime.InteropServices.ComTypes.FILETIME lpLastWriteTime);
480
481        /// <summary>
482        /// Sets the date and time that the specified file or directory was created,
483        /// last accessed, or last modified.
484        /// </summary>
485        /// <param name="hFile">A handle to the file or directory. The handle must
486        /// have been created using the CreateFile function with the
487        /// FILE_WRITE_ATTRIBUTES access right. For more information, see File
488        /// Security and Access Rights.</param>
489        /// <param name="lpCreationTime">A pointer to a FILETIME structure that
490        /// contains the new creation date and time for the file or directory.
491        /// This parameter can be NULL if the application does not need to change
492        /// this information.</param>
493        /// <param name="lpLastAccessTime">A pointer to a FILETIME structure that
494        /// contains the new last access date and time for the file or directory.
495        /// The last access time includes the last time the file or directory was
496        /// written to, read from, or (in the case of executable files) run. This
497        /// parameter can be NULL if the application does not need to change this
498        /// information.
499        ///
500        /// To preserve the existing last access time for a file even after accessing
501        /// a file, call SetFileTime immediately after opening the file handle
502        /// with this parameter's FILETIME structure members initialized to
503        /// 0xFFFFFFFF.</param>
504        /// <param name="lpLastWriteTime">A pointer to a FILETIME structure that
505        /// contains the new last modified date and time for the file or directory.
506        /// This parameter can be NULL if the application does not need to change
507        /// this information.</param>
508        /// <returns>If the function succeeds, the return value is nonzero.
509        ///
510        /// If the function fails, the return value is zero. To get extended error
511        /// information, call GetLastError.</returns>
512        [DllImport("Kernel32.dll", SetLastError = true)]
513        [return: MarshalAs(UnmanagedType.Bool)]
514        public static extern bool SetFileTime(SafeFileHandle hFile,
515            ref System.Runtime.InteropServices.ComTypes.FILETIME lpCreationTime,
516            ref System.Runtime.InteropServices.ComTypes.FILETIME lpLastAccessTime,
517            ref System.Runtime.InteropServices.ComTypes.FILETIME lpLastWriteTime);
518
519        /// <summary>
520        /// Retrieves the name of a volume on a computer. FindFirstVolume is used
521        /// to begin scanning the volumes of a computer.
522        /// </summary>
523        /// <param name="lpszVolumeName">A pointer to a buffer that receives a
524        /// null-terminated string that specifies the unique volume name of the
525        /// first volume found.</param>
526        /// <param name="cchBufferLength">The length of the buffer to receive the
527        /// name, in TCHARs.</param>
528        /// <returns>If the function succeeds, the return value is a search handle
529        /// used in a subsequent call to the FindNextVolume and FindVolumeClose
530        /// functions.
531        ///
532        /// If the function fails to find any volumes, the return value is the
533        /// INVALID_HANDLE_VALUE error code. To get extended error information,
534        /// call GetLastError.</returns>
535        [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
536        public static extern SafeFileHandle FindFirstVolume(StringBuilder lpszVolumeName,
537            uint cchBufferLength);
538
539        /// <summary>
540        /// Continues a volume search started by a call to the FindFirstVolume
541        /// function. FindNextVolume finds one volume per call.
542        /// </summary>
543        /// <param name="hFindVolume">The volume search handle returned by a previous
544        /// call to the FindFirstVolume function.</param>
545        /// <param name="lpszVolumeName">A pointer to a string that receives the
546        /// unique volume name found.</param>
547        /// <param name="cchBufferLength">The length of the buffer that receives
548        /// the name, in TCHARs.</param>
549        /// <returns>If the function succeeds, the return value is nonzero.
550        ///
551        /// If the function fails, the return value is zero. To get extended error
552        /// information, call GetLastError. If no matching files can be found, the
553        /// GetLastError function returns the ERROR_NO_MORE_FILES error code. In
554        /// that case, close the search with the FindVolumeClose function.</returns>
555        [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
556        [return: MarshalAs(UnmanagedType.Bool)]
557        public static extern bool FindNextVolume(SafeHandle hFindVolume,
558            StringBuilder lpszVolumeName, uint cchBufferLength);
559
560        /// <summary>
561        /// Closes the specified volume search handle. The FindFirstVolume and
562        /// FindNextVolume functions use this search handle to locate volumes.
563        /// </summary>
564        /// <param name="hFindVolume">The volume search handle to be closed. This
565        /// handle must have been previously opened by the FindFirstVolume function.</param>
566        /// <returns>If the function succeeds, the return value is nonzero.
567        ///
568        /// If the function fails, the return value is zero. To get extended error
569        /// information, call GetLastError.</returns>
570        [DllImport("Kernel32.dll", SetLastError = true)]
571        [return: MarshalAs(UnmanagedType.Bool)]
572        public static extern bool FindVolumeClose(SafeHandle hFindVolume);
573
574        /// <summary>
575        /// Retrieves the name of a volume mount point on the specified volume.
576        /// FindFirstVolumeMountPoint is used to begin scanning the volume mount
577        /// points on a volume.
578        /// </summary>
579        /// <param name="lpszRootPathName">The unique volume name of the volume
580        /// to scan for volume mount points. A trailing backslash is required.</param>
581        /// <param name="lpszVolumeMountPoint">A pointer to a buffer that receives
582        /// the name of the first volume mount point found.</param>
583        /// <param name="cchBufferLength">The length of the buffer that receives
584        /// the volume mount point name, in TCHARs.</param>
585        /// <returns>If the function succeeds, the return value is a search handle
586        /// used in a subsequent call to the FindNextVolumeMountPoint and
587        /// FindVolumeMountPointClose functions.
588        ///
589        /// If the function fails to find a volume mount point on the volume, the
590        /// return value is the INVALID_HANDLE_VALUE error code. To get extended
591        /// error information, call GetLastError.</returns>
592        [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
593        public static extern SafeFileHandle FindFirstVolumeMountPoint(
594            string lpszRootPathName, StringBuilder lpszVolumeMountPoint,
595            uint cchBufferLength);
596
597        /// <summary>
598        /// Continues a volume mount point search started by a call to the
599        /// FindFirstVolumeMountPoint function. FindNextVolumeMountPoint finds one
600        /// volume mount point per call.
601        /// </summary>
602        /// <param name="hFindVolumeMountPoint">A mount-point search handle returned
603        /// by a previous call to the FindFirstVolumeMountPoint function.</param>
604        /// <param name="lpszVolumeMountPoint">A pointer to a buffer that receives
605        /// the name of the volume mount point found.</param>
606        /// <param name="cchBufferLength">The length of the buffer that receives
607        /// the names, in TCHARs.</param>
608        /// <returns>If the function succeeds, the return value is nonzero.
609        ///
610        /// If the function fails, the return value is zero. To get extended error
611        /// information, call GetLastError. If no matching files can be found, the
612        /// GetLastError function returns the ERROR_NO_MORE_FILES error code. In
613        /// that case, close the search with the FindVolumeMountPointClose function.</returns>
614        [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
615        [return: MarshalAs(UnmanagedType.Bool)]
616        public static extern bool FindNextVolumeMountPoint(
617            SafeHandle hFindVolumeMountPoint, StringBuilder lpszVolumeMountPoint,
618            uint cchBufferLength);
619
620        /// <summary>
621        /// Closes the specified mount-point search handle. The FindFirstVolumeMountPoint
622        /// and FindNextVolumeMountPoint  functions use this search handle to locate
623        /// volume mount points on a specified volume.
624        /// </summary>
625        /// <param name="hFindVolumeMountPoint">The mount-point search handle to
626        /// be closed. This handle must have been previously opened by the
627        /// FindFirstVolumeMountPoint function.</param>
628        /// <returns>If the function succeeds, the return value is nonzero.
629        ///
630        /// If the function fails, the return value is zero. To get extended error
631        /// information, call GetLastError.</returns>
632        [DllImport("Kernel32.dll", SetLastError = true)]
633        [return: MarshalAs(UnmanagedType.Bool)]
634        public static extern bool FindVolumeMountPointClose(SafeHandle hFindVolumeMountPoint);
635
636        /// <summary>
637        /// Retrieves information about the specified disk, including the amount
638        /// of free space on the disk.
639        ///
640        /// The GetDiskFreeSpace function cannot report volume sizes that are
641        /// greater than 2 gigabytes (GB). To ensure that your application works
642        /// with large capacity hard drives, use the GetDiskFreeSpaceEx function.
643        /// </summary>
644        /// <param name="lpRootPathName">The root directory of the disk for which
645        /// information is to be returned. If this parameter is NULL, the function
646        /// uses the root of the current disk. If this parameter is a UNC name,
647        /// it must include a trailing backslash (for example, \\MyServer\MyShare\).
648        /// Furthermore, a drive specification must have a trailing backslash
649        /// (for example, C:\). The calling application must have FILE_LIST_DIRECTORY
650        /// access rights for this directory.</param>
651        /// <param name="lpSectorsPerCluster">A pointer to a variable that receives
652        /// the number of sectors per cluster.</param>
653        /// <param name="lpBytesPerSector">A pointer to a variable that receives
654        /// the number of bytes per sector.</param>
655        /// <param name="lpNumberOfFreeClusters">A pointer to a variable that
656        /// receives the total number of free clusters on the disk that are
657        /// available to the user who is associated with the calling thread.
658        ///
659        /// If per-user disk quotas are in use, this value may be less than the
660        /// total number of free clusters on the disk.</param>
661        /// <param name="lpTotalNumberOfClusters">A pointer to a variable that
662        /// receives the total number of clusters on the disk that are available
663        /// to the user who is associated with the calling thread.
664        ///
665        /// If per-user disk quotas are in use, this value may be less than the
666        /// total number of clusters on the disk.</param>
667        /// <returns>If the function succeeds, the return value is true. To get
668        /// extended error information, call Marshal.GetLastWin32Error().</returns>
669        [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
670        [return: MarshalAs(UnmanagedType.Bool)]
671        public static extern bool GetDiskFreeSpace(
672            string lpRootPathName, out UInt32 lpSectorsPerCluster, out UInt32 lpBytesPerSector,
673            out UInt32 lpNumberOfFreeClusters, out UInt32 lpTotalNumberOfClusters);
674
675
676        /// <summary>
677        /// Retrieves information about the amount of space that is available on
678        /// a disk volume, which is the total amount of space, the total amount
679        /// of free space, and the total amount of free space available to the
680        /// user that is associated with the calling thread.
681        /// </summary>
682        /// <param name="lpDirectoryName">A directory on the disk.
683        ///
684        /// If this parameter is NULL, the function uses the root of the current
685        /// disk.
686        ///
687        /// If this parameter is a UNC name, it must include a trailing backslash,
688        /// for example, "\\MyServer\MyShare\".
689        ///
690        /// This parameter does not have to specify the root directory on a disk.
691        /// The function accepts any directory on a disk.
692        ///
693        /// The calling application must have FILE_LIST_DIRECTORY access rights
694        /// for this directory.</param>
695        /// <param name="lpFreeBytesAvailable">A pointer to a variable that receives
696        /// the total number of free bytes on a disk that are available to the
697        /// user who is associated with the calling thread.
698        ///
699        /// This parameter can be NULL.
700        ///
701        /// If per-user quotas are being used, this value may be less than the
702        /// total number of free bytes on a disk.</param>
703        /// <param name="lpTotalNumberOfBytes">A pointer to a variable that receives
704        /// the total number of bytes on a disk that are available to the user who
705        /// is associated with the calling thread.
706        ///
707        /// This parameter can be NULL.
708        ///
709        /// If per-user quotas are being used, this value may be less than the
710        /// total number of bytes on a disk.
711        ///
712        /// To determine the total number of bytes on a disk or volume, use
713        /// IOCTL_DISK_GET_LENGTH_INFO.</param>
714        /// <param name="lpTotalNumberOfFreeBytes">A pointer to a variable that
715        /// receives the total number of free bytes on a disk.
716        ///
717        /// This parameter can be NULL.</param>
718        /// <returns>If the function succeeds, the return value is nonzero.
719        ///
720        /// If the function fails, the return value is zero (0). To get extended
721        /// error information, call GetLastError.</returns>
722        [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
723        [return: MarshalAs(UnmanagedType.Bool)]
724        public static extern bool GetDiskFreeSpaceEx(
725            string lpDirectoryName,
726            out UInt64 lpFreeBytesAvailable,
727            out UInt64 lpTotalNumberOfBytes,
728            out UInt64 lpTotalNumberOfFreeBytes);
729
730        /// <summary>
731        /// Determines whether a disk drive is a removable, fixed, CD-ROM, RAM disk,
732        /// or network drive.
733        /// </summary>
734        /// <param name="lpRootPathName">The root directory for the drive.
735        ///
736        /// A trailing backslash is required. If this parameter is NULL, the function
737        /// uses the root of the current directory.</param>
738        /// <returns>The return value specifies the type of drive, which can be
739        /// one of the DriveInfo.DriveType values.</returns>
740        [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
741        public static extern uint GetDriveType(string lpRootPathName);
742
743        /// <summary>
744        /// Retrieves information about the file system and volume associated with
745        /// the specified root directory.
746        ///
747        /// To specify a handle when retrieving this information, use the
748        /// GetVolumeInformationByHandleW function.
749        ///
750        /// To retrieve the current compression state of a file or directory, use
751        /// FSCTL_GET_COMPRESSION.
752        /// </summary>
753        /// <param name="lpRootPathName">    A pointer to a string that contains
754        /// the root directory of the volume to be described.
755        ///
756        /// If this parameter is NULL, the root of the current directory is used.
757        /// A trailing backslash is required. For example, you specify
758        /// \\MyServer\MyShare as "\\MyServer\MyShare\", or the C drive as "C:\".</param>
759        /// <param name="lpVolumeNameBuffer">A pointer to a buffer that receives
760        /// the name of a specified volume. The maximum buffer size is MAX_PATH+1.</param>
761        /// <param name="nVolumeNameSize">The length of a volume name buffer, in
762        /// TCHARs. The maximum buffer size is MAX_PATH+1.
763        ///
764        /// This parameter is ignored if the volume name buffer is not supplied.</param>
765        /// <param name="lpVolumeSerialNumber">A pointer to a variable that receives
766        /// the volume serial number.
767        ///
768        /// This parameter can be NULL if the serial number is not required.
769        ///
770        /// This function returns the volume serial number that the operating system
771        /// assigns when a hard disk is formatted. To programmatically obtain the
772        /// hard disk's serial number that the manufacturer assigns, use the
773        /// Windows Management Instrumentation (WMI) Win32_PhysicalMedia property
774        /// SerialNumber.</param>
775        /// <param name="lpMaximumComponentLength">A pointer to a variable that
776        /// receives the maximum length, in TCHARs, of a file name component that
777        /// a specified file system supports.
778        ///
779        /// A file name component is the portion of a file name between backslashes.
780        ///
781        /// The value that is stored in the variable that *lpMaximumComponentLength
782        /// points to is used to indicate that a specified file system supports
783        /// long names. For example, for a FAT file system that supports long names,
784        /// the function stores the value 255, rather than the previous 8.3 indicator.
785        /// Long names can also be supported on systems that use the NTFS file system.</param>
786        /// <param name="lpFileSystemFlags">A pointer to a variable that receives
787        /// flags associated with the specified file system.
788        ///
789        /// This parameter can be one or more of the FS_FILE* flags. However,
790        /// FS_FILE_COMPRESSION and FS_VOL_IS_COMPRESSED are mutually exclusive.</param>
791        /// <param name="lpFileSystemNameBuffer">A pointer to a buffer that receives
792        /// the name of the file system, for example, the FAT file system or the
793        /// NTFS file system. The maximum buffer size is MAX_PATH+1.</param>
794        /// <param name="nFileSystemNameSize">The length of the file system name
795        /// buffer, in TCHARs. The maximum buffer size is MAX_PATH+1.
796        ///
797        /// This parameter is ignored if the file system name buffer is not supplied.</param>
798        /// <returns>If all the requested information is retrieved, the return value
799        /// is nonzero.
800        ///
801        ///
802        /// If not all the requested information is retrieved, the return value is
803        /// zero (0). To get extended error information, call GetLastError.</returns>
804        [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
805        [return: MarshalAs(UnmanagedType.Bool)]
806        public static extern bool GetVolumeInformation(
807            string lpRootPathName,
808            StringBuilder lpVolumeNameBuffer,
809            uint nVolumeNameSize,
810            out uint lpVolumeSerialNumber,
811            out uint lpMaximumComponentLength,
812            out uint lpFileSystemFlags,
813            StringBuilder lpFileSystemNameBuffer,
814            uint nFileSystemNameSize);
815
816        /// <summary>
817        /// Retrieves the unique volume name for the specified volume mount point or root directory.
818        /// </summary>
819        /// <param name="lpszVolumeMountPoint">The path of a volume mount point (with a trailing
820        /// backslash, "\") or a drive letter indicating a root directory (in the
821        /// form "D:\").</param>
822        /// <param name="lpszVolumeName">A pointer to a string that receives the
823        /// volume name. This name is a unique volume name of the form
824        /// "\\?\Volume{GUID}\" where GUID is the GUID that identifies the volume.</param>
825        /// <param name="cchBufferLength">The length of the output buffer, in TCHARs.
826        /// A reasonable size for the buffer to accommodate the largest possible
827        /// volume name is 50 characters.</param>
828        /// <returns>If the function succeeds, the return value is nonzero.
829        ///
830        /// If the function fails, the return value is zero. To get extended
831        /// error information, call GetLastError.</returns>
832        [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
833        [return: MarshalAs(UnmanagedType.Bool)]
834        public static extern bool GetVolumeNameForVolumeMountPoint(
835            string lpszVolumeMountPoint, StringBuilder lpszVolumeName,
836            uint cchBufferLength);
837
838        /// <summary>
839        /// Retrieves a list of path names for the specified volume name.
840        /// </summary>
841        /// <param name="lpszVolumeName">The volume name.</param>
842        /// <param name="lpszVolumePathNames">A pointer to a buffer that receives
843        /// the list of volume path names. The list is an array of null-terminated
844        /// strings terminated by an additional NULL character. If the buffer is
845        /// not large enough to hold the complete list, the buffer holds as much
846        /// of the list as possible.</param>
847        /// <param name="cchBufferLength">The length of the lpszVolumePathNames
848        /// buffer, in TCHARs.</param>
849        /// <param name="lpcchReturnLength">If the call is successful, this parameter
850        /// is the number of TCHARs copied to the lpszVolumePathNames buffer. Otherwise,
851        /// this parameter is the size of the buffer required to hold the complete
852        /// list, in TCHARs.</param>
853        /// <returns></returns>
854        [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
855        [return: MarshalAs(UnmanagedType.Bool)]
856        public static extern bool GetVolumePathNamesForVolumeName(
857            string lpszVolumeName, StringBuilder lpszVolumePathNames, uint cchBufferLength,
858            out uint lpcchReturnLength);
859
860        public const int MaxPath = 260;
861        public const int LongPath = 32768;
862
863        /// <summary>
864        /// Retrieves the product type for the operating system on the local computer, and
865        /// maps the type to the product types supported by the specified operating system.
866        /// </summary>
867        /// <param name="dwOSMajorVersion">The major version number of the operating system.
868        /// The minimum value is 6.
869        ///
870        /// The combination of the dwOSMajorVersion, dwOSMinorVersion, dwSpMajorVersion,
871        /// and dwSpMinorVersion parameters describes the maximum target operating system
872        /// version for the application. For example, Windows Vista and Windows Server
873        /// 2008 are version 6.0.0.0 and Windows 7 and Windows Server 2008 R2 are version
874        /// 6.1.0.0.</param>
875        /// <param name="dwOSMinorVersion">The minor version number of the operating
876        /// system. The minimum value is 0.</param>
877        /// <param name="dwSpMajorVersion">The major version number of the operating
878        /// system service pack. The minimum value is 0.</param>
879        /// <param name="dwSpMinorVersion">The minor version number of the operating
880        /// system service pack. The minimum value is 0.</param>
881        /// <param name="pdwReturnedProductType">The product type. This parameter
882        /// cannot be NULL. If the specified operating system is less than the
883        /// current operating system, this information is mapped to the types
884        /// supported by the specified operating system. If the specified operating
885        /// system is greater than the highest supported operating system, this
886        /// information is mapped to the types supported by the current operating system.
887        ///
888        /// If the product has not been activated and is no longer in the grace period,
889        /// this parameter is set to PRODUCT_UNLICENSED (0xABCDABCD).</param>
890        /// <returns>If the function succeeds, the return value is a nonzero value.
891        /// If the software license is invalid or expired, the function succeeds
892        /// but the pdwReturnedProductType parameter is set to PRODUCT_UNLICENSED.
893        ///
894        /// If the function fails, the return value is zero. This function fails if
895        /// one of the input parameters is invalid.</returns>
896        [DllImport("Kernel32.dll", CharSet = CharSet.Unicode)]
897        public static extern bool GetProductInfo(uint dwOSMajorVersion,
898            uint dwOSMinorVersion, uint dwSpMajorVersion, uint dwSpMinorVersion,
899            out WindowsEditions pdwReturnedProductType);
900
901    }
902}
Note: See TracBrowser for help on using the repository browser.