using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security; using System.Text; using System.Threading; using Vanara.InteropServices; using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; namespace Vanara.PInvoke { /// Fields, enums, functions and structures for kernel32.dll. public static partial class Kernel32 { /// Always create new, overwriting any existing. [PInvokeData("fileapi.h")] public const uint CREATE_ALWAYS = 2; /// Create new if one does not already exist. [PInvokeData("fileapi.h")] public const uint CREATE_NEW = 1; /// A value returned when invalid file attributes are found. [PInvokeData("fileapi.h")] public const int INVALID_FILE_ATTRIBUTES = -2; /// A value returned by when the function fails. [PInvokeData("fileapi.h")] public const uint INVALID_FILE_SIZE = 0xFFFFFFFF; /// A value returned then a file pointer cannot be set. [PInvokeData("fileapi.h")] public const int INVALID_SET_FILE_POINTER = -1; /// Alway open, creating new if doesn't exist. [PInvokeData("fileapi.h")] public const uint OPEN_ALWAYS = 4; /// Open existing. [PInvokeData("fileapi.h")] public const uint OPEN_EXISTING = 3; /// Truncate existing. [PInvokeData("fileapi.h")] public const uint TRUNCATE_EXISTING = 5; /// /// An application-defined callback function used with the ReadFileEx and WriteFileEx functions. It is called when the asynchronous /// input and output (I/O) operation is completed or canceled and the calling thread is in an alertable state (by using the SleepEx, /// MsgWaitForMultipleObjectsEx, WaitForSingleObjectEx, or WaitForMultipleObjectsEx function with the fAlertable parameter set to TRUE). /// /// The I/O completion status. This parameter can be one of the system error codes. /// The number of bytes transferred. If an error occurs, this parameter is zero. /// /// A pointer to the OVERLAPPED structure specified by the asynchronous I/O function. /// /// The system does not use the OVERLAPPED structure after the completion routine is called, so the completion routine can deallocate /// the memory used by the overlapped structure. /// /// public delegate void FileIOCompletionRoutine(uint dwErrorCode, uint dwNumberOfBytesTransfered, IntPtr lpOverlapped); /// /// An application-defined callback function used with the ReadFileEx and WriteFileEx functions. It is called when the asynchronous /// input and output (I/O) operation is completed or canceled and the calling thread is in an alertable state (by using the SleepEx, /// MsgWaitForMultipleObjectsEx, WaitForSingleObjectEx, or WaitForMultipleObjectsEx function with the fAlertable parameter set to TRUE). /// /// The I/O completion status. This parameter can be one of the system error codes. /// The number of bytes transferred. If an error occurs, this parameter is zero. /// /// A pointer to the OVERLAPPED structure specified by the asynchronous I/O function. /// /// The system does not use the OVERLAPPED structure after the completion routine is called, so the completion routine can deallocate /// the memory used by the overlapped structure. /// /// public unsafe delegate void FileIOCompletionRoutineUnsafe(uint dwErrorCode, uint dwNumberOfBytesTransfered, NativeOverlapped* lpOverlapped); /// The controllable aspects of the DefineDosDevice function. [Flags] public enum DDD { /// Uses the lpTargetPath string as is. Otherwise, it is converted from an MS-DOS path to a path. DDD_RAW_TARGET_PATH = 0x00000001, /// /// Removes the specified definition for the specified device. To determine which definition to remove, the function walks the /// list of mappings for the device, looking for a match of lpTargetPath against a prefix of each mapping associated with this /// device. The first mapping that matches is the one removed, and then the function returns. /// /// If lpTargetPath is NULL or a pointer to a NULL string, the function will remove the first mapping associated with the device /// and pop the most recent one pushed. If there is nothing left to pop, the device name will be removed. /// /// /// If this value is not specified, the string pointed to by the lpTargetPath parameter will become the new mapping for this device. /// /// DDD_REMOVE_DEFINITION = 0x00000002, /// /// If this value is specified along with DDD_REMOVE_DEFINITION, the function will use an exact match to determine which mapping /// to remove. Use this value to ensure that you do not delete something that you did not define. /// DDD_EXACT_MATCH_ON_REMOVE = 0x00000004, /// /// Do not broadcast the WM_SETTINGCHANGE message. By default, this message is broadcast to notify the shell and applications of /// the change. /// DDD_NO_BROADCAST_SYSTEM = 0x00000008, /// Undocumented. DDD_LUID_BROADCAST_DRIVE = 0x00000010 } /// Specifies the type of drive. public enum DRIVE_TYPE { /// The drive type cannot be determined. DRIVE_UNKNOWN = 0, /// The root path is invalid; for example, there is no volume mounted at the specified path. DRIVE_NO_ROOT_DIR = 1, /// The drive has removable media; for example, a floppy drive, thumb drive, or flash card reader. DRIVE_REMOVABLE = 2, /// The drive has fixed media; for example, a hard disk drive or flash drive. DRIVE_FIXED = 3, /// The drive is a remote (network) drive. DRIVE_REMOTE = 4, /// The drive is a CD-ROM drive. DRIVE_CDROM = 5, /// The drive is a RAM disk. DRIVE_RAMDISK = 6, } /// The filter conditions that satisfy a change notification wait. [Flags] public enum FILE_NOTIFY_CHANGE { /// /// Any file name change in the watched directory or subtree causes a change notification wait operation to return. Changes /// include renaming, creating, or deleting a file name. /// FILE_NOTIFY_CHANGE_FILE_NAME = 0x00000001, /// /// Any directory-name change in the watched directory or subtree causes a change notification wait operation to return. Changes /// include creating or deleting a directory. /// FILE_NOTIFY_CHANGE_DIR_NAME = 0x00000002, /// Any attribute change in the watched directory or subtree causes a change notification wait operation to return. FILE_NOTIFY_CHANGE_ATTRIBUTES = 0x00000004, /// /// Any file-size change in the watched directory or subtree causes a change notification wait operation to return. The operating /// system detects a change in file size only when the file is written to the disk. For operating systems that use extensive /// caching, detection occurs only when the cache is sufficiently flushed. /// FILE_NOTIFY_CHANGE_SIZE = 0x00000008, /// /// Any change to the last write-time of files in the watched directory or subtree causes a change notification wait operation to /// return. The operating system detects a change to the last write-time only when the file is written to the disk. For operating /// systems that use extensive caching, detection occurs only when the cache is sufficiently flushed. /// FILE_NOTIFY_CHANGE_LAST_WRITE = 0x00000010, /// /// Any change to the last access time of files in the watched directory or subtree causes a change notification wait operation /// to return. /// FILE_NOTIFY_CHANGE_LAST_ACCESS = 0x00000020, /// /// Any change to the creation time of files in the watched directory or subtree causes a change notification wait operation to return. /// FILE_NOTIFY_CHANGE_CREATION = 0x00000040, /// /// Any security-descriptor change in the watched directory or subtree causes a change notification wait operation to return. /// FILE_NOTIFY_CHANGE_SECURITY = 0x00000100, } /// Options for file and other type creation or opening. [PInvokeData("fileapi.h")] public enum CreationOption { /// Create new if one does not already exist. CREATE_NEW = 1, /// Always create new, overwriting any existing. CREATE_ALWAYS = 2, /// Open existing. OPEN_EXISTING = 3, /// Alway open, creating new if doesn't exist. OPEN_ALWAYS = 4, /// Truncate existing. TRUNCATE_EXISTING = 5, } /// File type values returned by . [PInvokeData("WinUser.h", MSDNShortId = "aa364960")] [Flags] public enum FileType { /// The specified file is a character file, typically an LPT device or a console. FILE_TYPE_CHAR = 0x0002, /// The specified file is a disk file. FILE_TYPE_DISK = 0x0001, /// The specified file is a socket, a named pipe, or an anonymous pipe. FILE_TYPE_PIPE = 0x0003, /// Unused. FILE_TYPE_REMOTE = 0x8000, /// Either the type of the specified file is unknown, or the function failed. FILE_TYPE_UNKNOWN = 0x0000, } /// Specifies additional flags that control the search. [Flags] public enum FIND_FIRST { /// Searches are case-sensitive. FIND_FIRST_EX_CASE_SENSITIVE = 1, /// /// Uses a larger buffer for directory queries, which can increase performance of the find operation. This value is not supported /// until Windows Server 2008 R2 and Windows 7. /// FIND_FIRST_EX_LARGE_FETCH = 2, /// /// Limits the results to files that are physically on disk. This flag is only relevant when a file virtualization filter is present. /// FIND_FIRST_EX_ON_DISK_ENTRIES_ONLY = 4 } /// /// Defines values that are used with the FindFirstFileEx function to specify the information level of the returned data. /// public enum FINDEX_INFO_LEVELS { /// /// The FindFirstFileEx function retrieves a standard set of attribute information. The data is returned in a WIN32_FIND_DATA structure. /// FindExInfoStandard, /// /// The FindFirstFileEx function does not query the short file name, improving overall enumeration speed. The data is returned in /// a WIN32_FIND_DATA structure, and the cAlternateFileName member is always a NULL string. /// /// Windows Server 2008, Windows Vista, Windows Server 2003 and Windows XP: This value is not supported until Windows /// Server 2008 R2 and Windows 7. /// /// FindExInfoBasic, /// /// The FindFirstFileEx function does not query the short file name, improving overall enumeration speed. The data is returned in /// a WIN32_FIND_DATA structure, and the cAlternateFileName member is always a NULL string. /// FindExInfoMaxInfoLevel, } /// Defines values that are used with the FindFirstFileEx function to specify the type of filtering to perform. public enum FINDEX_SEARCH_OPS { /// /// The search for a file that matches a specified file name. The lpSearchFilter parameter of FindFirstFileEx must be NULL when /// this search operation is used. /// FindExSearchNameMatch, /// /// This is an advisory flag. If the file system supports directory filtering, the function searches for a file that matches the /// specified name and is also a directory. If the file system does not support directory filtering, this flag is silently ignored. /// The lpSearchFilter parameter of the FindFirstFileEx function must be NULL when this search value is used. /// /// If directory filtering is desired, this flag can be used on all file systems, but because it is an advisory flag and only /// affects file systems that support it, the application must examine the file attribute data stored in the lpFindFileData /// parameter of the FindFirstFileEx function to determine whether the function has returned a handle to a directory. /// /// FindExSearchLimitToDirectories, /// This filtering type is not available. FindExSearchLimitToDevices } /// /// Defines values that are used with the GetFileAttributesEx and GetFileAttributesTransacted functions to specify the information /// level of the returned data. /// public enum GET_FILEEX_INFO_LEVELS { /// /// The GetFileAttributesEx or GetFileAttributesTransacted function retrieves a standard set of attribute information. The data /// is returned in a WIN32_FILE_ATTRIBUTE_DATA structure. /// GetFileExInfoStandard, } /// Options for . [PInvokeData("minwinbase.h", MSDNShortId = "aa365203")] [Flags] public enum LOCKFILE { /// The function returns immediately if it is unable to acquire the requested lock. Otherwise, it waits. LOCKFILE_FAIL_IMMEDIATELY = 0x00000001, /// The function requests an exclusive lock. Otherwise, it requests a shared lock. LOCKFILE_EXCLUSIVE_LOCK = 0x00000002 } /// /// Reads data from the specified file or input/output (I/O) device. Reads occur at the position specified by the file pointer if /// supported by the device. /// /// /// A handle to the device (for example, a file, file stream, physical disk, volume, console buffer, tape drive, socket, /// communications resource, mailslot, or pipe). The hFile parameter must have been created with read access. /// /// A pointer to the buffer that receives the data read from a file or device. /// The maximum number of bytes to be read. /// An AsyncCallback delegate that references the method to invoke when the operation is complete. /// /// A user-defined object that contains information about the operation. This object is passed to the requestCallback delegate when /// the operation is complete. /// /// An IAsyncResult instance that references the asynchronous request. public static unsafe IAsyncResult BeginReadFile(HFILE hFile, byte[] buffer, uint numberOfBytesToRead, AsyncCallback requestCallback, object stateObject) { var ar = OverlappedAsync.SetupOverlappedFunction(hFile, requestCallback, stateObject); fixed (byte* pIn = buffer) { var ret = ReadFile(hFile, pIn, numberOfBytesToRead, IntPtr.Zero, ar.Overlapped); return OverlappedAsync.EvaluateOverlappedFunction(ar, ret); } } /// /// Writes data to the specified file or input/output (I/O) device. /// /// This function is designed for both synchronous and asynchronous operation. For a similar function designed solely for /// asynchronous operation, see WriteFileEx. /// /// /// /// A handle to the file or I/O device (for example, a file, file stream, physical disk, volume, console buffer, tape drive, socket, /// communications resource, mailslot, or pipe). /// /// The hFile parameter must have been created with the write access. For more information, see Generic Access Rights and File /// Security and Access Rights. /// /// /// For asynchronous write operations, hFile can be any handle opened with the CreateFile function using the FILE_FLAG_OVERLAPPED /// flag or a socket handle returned by the socket or accept function. /// /// /// /// A pointer to the buffer containing the data to be written to the file or device. /// /// This buffer must remain valid for the duration of the write operation. The caller must not use this buffer until the write /// operation is completed. /// /// /// /// The number of bytes to be written to the file or device. /// /// A value of zero specifies a null write operation. The behavior of a null write operation depends on the underlying file system or /// communications technology. /// /// /// Windows Server 2003 and Windows XP: Pipe write operations across a network are limited in size per write. The amount varies per /// platform. For x86 platforms it's 63.97 MB. For x64 platforms it's 31.97 MB. For Itanium it's 63.95 MB. For more information /// regarding pipes, see the Remarks section. /// /// /// An AsyncCallback delegate that references the method to invoke when the operation is complete. /// /// A user-defined object that contains information about the operation. This object is passed to the requestCallback delegate when /// the operation is complete. /// /// An IAsyncResult instance that references the asynchronous request. public static unsafe IAsyncResult BeginWriteFile(HFILE hFile, byte[] buffer, uint numberOfBytesToWrite, AsyncCallback requestCallback, object stateObject) { var ar = OverlappedAsync.SetupOverlappedFunction(hFile, requestCallback, stateObject); fixed (byte* pIn = buffer) { var ret = WriteFile(hFile, pIn, numberOfBytesToWrite, null, ar.Overlapped); return OverlappedAsync.EvaluateOverlappedFunction(ar, ret); } } /// /// Compares two file times. /// /// /// A pointer to a FILETIME structure that specifies the first file time. /// /// /// A pointer to a FILETIME structure that specifies the second file time. /// /// /// The return value is one of the following values. /// /// /// Return value /// Description /// /// /// -1 /// First file time is earlier than second file time. /// /// /// 0 /// First file time is equal to second file time. /// /// /// 1 /// First file time is later than second file time. /// /// /// // LONG WINAPI CompareFileTime( _In_ const FILETIME *lpFileTime1, _In_ const FILETIME *lpFileTime2); [DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)] [PInvokeData("FileAPI.h", MSDNShortId = "ms724214")] public static extern int CompareFileTime(in FILETIME lpFileTime1, in FILETIME lpFileTime2); /// /// Creates a new directory. If the underlying file system supports security on files and directories, the function applies a /// specified security descriptor to the new directory. /// /// The path of the directory to be created. /// /// A pointer to a SECURITY_ATTRIBUTES structure. The lpSecurityDescriptor member of the structure specifies a security descriptor /// for the new directory. If lpSecurityAttributes is NULL, the directory gets a default security descriptor. The ACLs in the default /// security descriptor for a directory are inherited from its parent directory. /// /// /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero.To get extended error /// information, call GetLastError. /// [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [PInvokeData("FileAPI.h", MSDNShortId = "aa363855")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool CreateDirectory(string lpPathName, [In, Optional] SECURITY_ATTRIBUTES lpSecurityAttributes); /// /// Creates or opens a file or I/O device. The most commonly used I/O devices are as follows: file, file stream, directory, physical /// disk, volume, console buffer, tape drive, communications resource, mailslot, and pipe. The function returns a handle that can be /// used to access the file or device for various types of I/O depending on the file or device and the flags and attributes specified. /// /// /// The name of the file or device to be created or opened. You may use either forward slashes (/) or backslashes (\) in this name. /// /// In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to 32,767 wide characters, /// call the Unicode version of the function and prepend "\\?\" to the path. For more information, see Naming Files, Paths, and Namespaces. /// /// For information on special device names, see Defining an MS-DOS Device Name. /// /// To create a file stream, specify the name of the file, a colon, and then the name of the stream. For more information, see File Streams. /// /// Starting with Windows 10, version 1607, for the Unicode version of this function (CreateFileW), you can opt-in /// to remove the MAX_PATH limitation without prepending "\\?\". See the "Maximum Path Length Limitation" section of Naming Files, /// Paths, and Namespaces for details. /// /// /// The requested access to the file or device, which can be summarized as read, write, both or neither zero). /// /// The most commonly used values are GENERIC_READ, GENERIC_WRITE, or both (GENERIC_READ | GENERIC_WRITE). For more information, see /// Generic Access Rights, File Security and Access Rights, File Access Rights Constants, and ACCESS_MASK. /// /// /// If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes without /// accessing that file or device, even if GENERIC_READ access would have been denied. /// /// /// You cannot request an access mode that conflicts with the sharing mode that is specified by the dwShareMode parameter in an open /// request that already has an open handle. /// /// /// /// The requested sharing mode of the file or device, which can be read, write, both, delete, all of these, or none (refer to the /// following table). Access requests to attributes or extended attributes are not affected by this flag. /// /// If this parameter is zero and CreateFile succeeds, the file or device cannot be shared and cannot be opened again until the /// handle to the file or device is closed. For more information, see the Remarks section. /// /// /// You cannot request a sharing mode that conflicts with the access mode that is specified in an existing request that has an open /// handle. CreateFile would fail and the GetLastError function would return ERROR_SHARING_VIOLATION. /// /// /// To enable a process to share a file or device while another process has the file or device open, use a compatible combination of /// one or more of the following values. For more information about valid combinations of this parameter with the dwDesiredAccess /// parameter, see Creating and Opening Files. /// /// The sharing options for each open handle remain in effect until that handle is closed, regardless of process context. /// /// /// A pointer to a SECURITY_ATTRIBUTES structure that contains two separate but related data members: an optional security /// descriptor, and a Boolean value that determines whether the returned handle can be inherited by child processes. /// This parameter can be NULL. /// /// If this parameter is NULL, the handle returned by CreateFile cannot be inherited by any child processes the application may /// create and the file or device associated with the returned handle gets a default security descriptor. /// /// /// The lpSecurityDescriptor member of the structure specifies a SECURITY_DESCRIPTOR for a file or device. If this member is NULL, /// the file or device associated with the returned handle is assigned a default security descriptor. /// /// /// CreateFile ignores the lpSecurityDescriptor member when opening an existing file or device, but continues to use the /// bInheritHandle member. /// /// The bInheritHandlemember of the structure specifies whether the returned handle can be inherited. /// /// /// An action to take on a file or device that exists or does not exist. /// For devices other than files, this parameter is usually set to OPEN_EXISTING. /// /// /// The file or device attributes and flags, FILE_ATTRIBUTE_NORMAL being the most common default value for files. /// /// This parameter can include any combination of the available file attributes (FILE_ATTRIBUTE_*). All other file attributes /// override FILE_ATTRIBUTE_NORMAL. /// /// /// This parameter can also contain combinations of flags (FILE_FLAG_*) for control of file or device caching behavior, access modes, /// and other special-purpose flags. These combine with any FILE_ATTRIBUTE_* values. /// /// /// This parameter can also contain Security Quality of Service (SQOS) information by specifying the SECURITY_SQOS_PRESENT flag. /// Additional SQOS-related flags information is presented in the table following the attributes and flags tables. /// /// When CreateFile opens an existing file, it generally combines the file flags with the file attributes of the existing file, /// and ignores any file attributes supplied as part of dwFlagsAndAttributes. Special cases are detailed in Creating and Opening Files. /// /// Some of the following file attributes and flags may only apply to files and not necessarily all other types of devices that /// CreateFile can open. For additional information, see the Remarks section of this topic and Creating and Opening Files. /// /// /// For more advanced access to file attributes, see SetFileAttributes. For a complete list of all file attributes with their values /// and descriptions, see File Attribute Constants. /// /// /// /// A valid handle to a template file with the GENERIC_READ access right. The template file supplies file attributes and extended /// attributes for the file that is being created. /// This parameter can be NULL. /// When opening an existing file, CreateFile ignores this parameter. /// /// When opening a new encrypted file, the file inherits the discretionary access control list from its parent directory. For /// additional information, see File Encryption. /// /// /// /// If the function succeeds, the return value is an open handle to the specified file, device, named pipe, or mail slot. /// If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call GetLastError. /// [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [PInvokeData("FileAPI.h", MSDNShortId = "aa363858")] public static extern SafeHFILE CreateFile(string lpFileName, FileAccess dwDesiredAccess, FileShare dwShareMode, [Optional] SECURITY_ATTRIBUTES lpSecurityAttributes, FileMode dwCreationDisposition, FileFlagsAndAttributes dwFlagsAndAttributes, [Optional] HFILE hTemplateFile); /// /// /// Creates or opens a file or I/O device. The most commonly used I/O devices are as follows: file, file stream, directory, physical /// disk, volume, console buffer, tape drive, communications resource, mailslot, and pipe. The function returns a handle that can be /// used to access the file or device for various types of I/O depending on the file or device and the flags and attributes specified. /// /// /// When called from a Windows Store app, CreateFile2 is simplified. You can open only files or directories inside the /// ApplicationData.LocalFolder or Package.InstalledLocation directories. You can't open named pipes or mailslots or create encrypted /// files ( FILE_ATTRIBUTE_ENCRYPTED). /// /// /// Note We refer here to the app's local folder and the package's installed location, not additional packages in the package /// graph, like resource packages. CreateFile2 doesn't support opening files in additional packages in the package graph. For /// example, suppose an app has a dependency on WinJS. The app can call CreateFile2 to open a file in its package but not in /// the WinJS package. /// /// /// To perform this operation as a transacted operation, which results in a handle that can be used for transacted I/O, use the /// CreateFileTransacted function. /// /// /// /// The name of the file or device to be created or opened. /// For information on special device names, see Defining an MS-DOS Device Name. /// /// To create a file stream, specify the name of the file, a colon, and then the name of the stream. For more information, see File Streams. /// /// /// Tip Starting with Windows 10, version 1607, you can opt-in to remove the MAX_PATH limitation without prepending /// "\\?\". See the "Maximum Path Length Limitation" section of Naming Files, Paths, and Namespaces for details. /// /// /// /// The requested access to the file or device, which can be summarized as read, write, both or neither zero). /// /// The most commonly used values are GENERIC_READ, GENERIC_WRITE, or both (). For more information, see Generic Access /// Rights, File Security and Access Rights, File Access Rights Constants, and ACCESS_MASK. /// /// /// If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes without /// accessing that file or device, even if GENERIC_READ access would have been denied. /// /// /// You cannot request an access mode that conflicts with the sharing mode that is specified by the dwShareMode parameter in an open /// request that already has an open handle. /// /// For more information, see the Remarks section of this topic and Creating and Opening Files. /// /// /// /// The requested sharing mode of the file or device, which can be read, write, both, delete, all of these, or none (refer to the /// following table). Access requests to attributes or extended attributes are not affected by this flag. /// /// /// If this parameter is zero and CreateFile2 succeeds, the file or device cannot be shared and cannot be opened again until /// the handle to the file or device is closed. For more information, see the Remarks section. /// /// /// You cannot request a sharing mode that conflicts with the access mode that is specified in an existing request that has an open /// handle. CreateFile2 would fail and the GetLastError function would return ERROR_SHARING_VIOLATION. /// /// /// To enable a process to share a file or device while another process has the file or device open, use a compatible combination of /// one or more of the following values. For more information about valid combinations of this parameter with the dwDesiredAccess /// parameter, see Creating and Opening Files. /// /// /// Note The sharing options for each open handle remain in effect until that handle is closed, regardless of process context. /// /// /// /// Value /// Meaning /// /// /// 0 0x00000000 /// /// Prevents other processes from opening a file or device if they request delete, read, or write access. Exclusive access to a file /// or directory is only granted if the application has write access to the file. /// /// /// /// FILE_SHARE_DELETE 0x00000004 /// /// Enables subsequent open operations on a file or device to request delete access. Otherwise, other processes cannot open the file /// or device if they request delete access. If this flag is not specified, but the file or device has been opened for delete access, /// the function fails. /// /// /// /// FILE_SHARE_READ 0x00000001 /// /// Enables subsequent open operations on a file or device to request read access. Otherwise, other processes cannot open the file or /// device if they request read access. If this flag is not specified, but the file or device has been opened for read access, the /// function fails. If a file or directory is being opened and this flag is not specified, and the caller does not have write access /// to the file or directory, the function fails. /// /// /// /// FILE_SHARE_WRITE 0x00000002 /// /// Enables subsequent open operations on a file or device to request write access. Otherwise, other processes cannot open the file /// or device if they request write access. If this flag is not specified, but the file or device has been opened for write access or /// has a file mapping with write access, the function fails. /// /// /// /// /// /// An action to take on a file or device that exists or does not exist. /// For devices other than files, this parameter is usually set to OPEN_EXISTING. /// For more information, see the Remarks section. /// This parameter must be one of the following values, which cannot be combined: /// /// /// Value /// Meaning /// /// /// CREATE_ALWAYS 2 /// /// Creates a new file, always. If the specified file exists and is writable, the function overwrites the file, the function /// succeeds, and last-error code is set to ERROR_ALREADY_EXISTS (183). If the specified file does not exist and is a valid path, a /// new file is created, the function succeeds, and the last-error code is set to zero. For more information, see the Remarks section /// of this topic. /// /// /// /// CREATE_NEW 1 /// /// Creates a new file, only if it does not already exist. If the specified file exists, the function fails and the last-error code /// is set to ERROR_FILE_EXISTS (80). If the specified file does not exist and is a valid path to a writable location, a new file is created. /// /// /// /// OPEN_ALWAYS 4 /// /// Opens a file, always. If the specified file exists, the function succeeds and the last-error code is set to ERROR_ALREADY_EXISTS /// (183). If the specified file does not exist and is a valid path to a writable location, the function creates a file and the /// last-error code is set to zero. /// /// /// /// OPEN_EXISTING 3 /// /// Opens a file or device, only if it exists. If the specified file or device does not exist, the function fails and the last-error /// code is set to ERROR_FILE_NOT_FOUND (2). For more information about devices, see the Remarks section. /// /// /// /// TRUNCATE_EXISTING 5 /// /// Opens a file and truncates it so that its size is zero bytes, only if it exists. If the specified file does not exist, the /// function fails and the last-error code is set to ERROR_FILE_NOT_FOUND (2). The calling process must open the file with the /// GENERIC_WRITE bit set as part of the dwDesiredAccess parameter. /// /// /// /// /// Pointer to an optional CREATEFILE2_EXTENDED_PARAMETERS structure. /// /// If the function succeeds, the return value is an open handle to the specified file, device, named pipe, or mail slot. /// If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call GetLastError. /// /// /// /// To compile an application that uses the CreateFile2 function, define the _WIN32_WINNT macro as 0x0602 or later. For /// more information, see Using the Windows Headers. /// /// /// CreateFile2 supports file interaction and most other types of I/O devices and mechanisms available to Windows developers. /// This section attempts to cover the varied issues developers may experience when using CreateFile2 in different contexts /// and with different I/O types. The text attempts to use the word file only when referring specifically to data stored in an actual /// file on a file system. However, some uses of file may be referring more generally to an I/O object that supports file-like /// mechanisms. This liberal use of the term file is particularly prevalent in constant names and parameter names because of the /// previously mentioned historical reasons. /// /// /// When an application is finished using the object handle returned by CreateFile2, use the CloseHandle function to close the /// handle. This not only frees up system resources, but can have wider influence on things like sharing the file or device and /// committing data to disk. Specifics are noted within this topic as appropriate. /// /// /// Some file systems, such as the NTFS file system, support compression or encryption for individual files and directories. On /// volumes that have a mounted file system with this support, a new file inherits the compression and encryption attributes of its directory. /// /// /// You cannot use CreateFile2 to control compression, decompression, or decryption on a file or directory. For more /// information, see Creating and Opening Files, File Compression and Decompression, and File Encryption. /// /// /// If the lpSecurityAttributes member of the CREATEFILE2_EXTENDED_PARAMETERS structure passed in the pCreateExParams /// parameter is NULL, the handle returned by CreateFile2 cannot be inherited by any child processes your application /// may create. The following information regarding this member also applies: /// /// /// /// /// If the bInheritHandle member variable is not FALSE, which is any nonzero value, then the handle can be inherited. /// Therefore it is critical this structure member be properly initialized to FALSE if you do not intend the handle to be inheritable. /// /// /// /// /// The access control lists (ACL) in the default security descriptor for a file or directory are inherited from its parent directory. /// /// /// /// /// The target file system must support security on files and directories for the lpSecurityDescriptor member to have an /// effect on them, which can be determined by using GetVolumeInformation. /// /// /// /// In Windows 8 and Windows Server 2012, this function is supported by the following technologies. /// /// /// Technology /// Supported /// /// /// Server Message Block (SMB) 3.0 protocol /// Yes /// /// /// SMB 3.0 Transparent Failover (TFO) /// No /// /// /// SMB 3.0 with Scale-out File Shares (SO) /// No /// /// /// Cluster Shared Volume File System (CsvFS) /// Yes /// /// /// Resilient File System (ReFS) /// Yes /// /// /// Symbolic Link Behavior /// /// If the call to this function creates a file, there is no change in behavior. Also, consider the following information regarding /// FILE_FLAG_OPEN_REPARSE_POINT flag for the dwFileFlags member of the CREATEFILE2_EXTENDED_PARAMETERS structure /// passed in the pCreateExParams parameter: /// /// /// /// If FILE_FLAG_OPEN_REPARSE_POINT is specified: /// /// /// If FILE_FLAG_OPEN_REPARSE_POINT is not specified: /// /// /// Files /// /// If you rename or delete a file and then restore it shortly afterward, the system searches the cache for file information to /// restore. Cached information includes its short/long name pair and creation time. /// /// /// If you call CreateFile2 on a file that is pending deletion as a result of a previous call to DeleteFile, the function /// fails. The operating system delays file deletion until all handles to the file are closed. GetLastError returns ERROR_ACCESS_DENIED. /// /// /// The dwDesiredAccess parameter can be zero, allowing the application to query file attributes without accessing the file if the /// application is running with adequate security settings. This is useful to test for the existence of a file without opening it for /// read and/or write access, or to obtain other statistics about the file or directory. See Obtaining and Setting File Information /// and GetFileInformationByHandle. /// /// /// When an application creates a file across a network, it is better to use for dwDesiredAccess than to use GENERIC_WRITE /// alone. The resulting code is faster, because the redirector can use the cache manager and send fewer SMBs with more data. This /// combination also avoids an issue where writing to a file across a network can occasionally return ERROR_ACCESS_DENIED. /// /// For more information, see Creating and Opening Files. /// File Streams /// /// On NTFS file systems, you can use CreateFile2 to create separate streams within a file. For more information, see File Streams. /// /// Directories /// /// An application cannot create a directory by using CreateFile2, therefore only the OPEN_EXISTING value is valid for /// dwCreationDisposition for this use case. To create a directory, the application must call CreateDirectory or CreateDirectoryEx. /// /// /// To open a directory using CreateFile2, specify the FILE_FLAG_BACKUP_SEMANTICS flag as part of dwFileFlags /// member of the CREATEFILE2_EXTENDED_PARAMETERS structure passed in the pCreateExParams parameter. Appropriate security checks /// still apply when this flag is used without SE_BACKUP_NAME and SE_RESTORE_NAME privileges. /// /// /// When using CreateFile2 to open a directory during defragmentation of a FAT or FAT32 file system volume, do not specify the /// MAXIMUM_ALLOWED access right. Access to the directory is denied if this is done. Specify the GENERIC_READ access /// right instead. /// /// For more information, see About Directory Management. /// Physical Disks and Volumes /// /// Direct access to the disk or to a volume is restricted. For more information, see "Changes to the file system and to the storage /// stack to restrict direct disk access and direct volume access in Windows Vista and in Windows Server 2008" in the Help and /// Support Knowledge Base at http://support.microsoft.com/kb/942448. /// /// /// You can use the CreateFile2 function to open a physical disk drive or a volume, which returns a direct access storage /// device (DASD) handle that can be used with the DeviceIoControl function. This enables you to access the disk or volume directly, /// for example such disk metadata as the partition table. However, this type of access also exposes the disk drive or volume to /// potential data loss, because an incorrect write to a disk using this mechanism could make its contents inaccessible to the /// operating system. To ensure data integrity, be sure to become familiar with DeviceIoControl and how other APIs behave /// differently with a direct access handle as opposed to a file system handle. /// /// The following requirements must be met for such a call to succeed: /// /// /// The caller must have administrative privileges. For more information, see Running with Special Privileges. /// /// /// The dwCreationDisposition parameter must have the OPEN_EXISTING flag. /// /// /// When opening a volume or floppy disk, the dwShareMode parameter must have the FILE_SHARE_WRITE flag. /// /// /// /// Note The dwDesiredAccess parameter can be zero, allowing the application to query device attributes without accessing a /// device. This is useful for an application to determine the size of a floppy disk drive and the formats it supports without /// requiring a floppy disk in a drive, for instance. It can also be used for reading statistics without requiring higher-level data /// read/write permission. /// /// /// When opening a physical drive x:, the lpFileName string should be the following form: "\\.\PhysicalDriveX". Hard disk numbers /// start at zero. The following table shows some examples of physical drive strings. /// /// /// /// String /// Meaning /// /// /// "\\.\PhysicalDrive0" /// Opens the first physical drive. /// /// /// "\\.\PhysicalDrive2" /// Opens the third physical drive. /// /// /// /// To obtain the physical drive identifier for a volume, open a handle to the volume and call the DeviceIoControl function with /// IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS. This control code returns the disk number and offset for each of the volume's one or more /// extents; a volume can span multiple physical disks. /// /// For an example of opening a physical drive, see Calling DeviceIoControl. /// /// When opening a volume or removable media drive (for example, a floppy disk drive or flash memory thumb drive), the lpFileName /// string should be the following form: "\.<i>X:". Do not use a trailing backslash (), which indicates the root directory of a /// drive. The following table shows some examples of drive strings. /// /// /// /// String /// Meaning /// /// /// "\\.\A:" /// Opens floppy disk drive A. /// /// /// "\\.\C:" /// Opens the C: volume. /// /// /// "\\.\C:\" /// Opens the file system of the C: volume. /// /// /// You can also open a volume by referring to its volume name. For more information, see Naming a Volume. /// /// A volume contains one or more mounted file systems. Volume handles can be opened as noncached at the discretion of the particular /// file system, even when the noncached option is not specified in CreateFile2. You should assume that all Microsoft file /// systems open volume handles as noncached. The restrictions on noncached I/O for files also apply to volumes. /// /// /// A file system may or may not require buffer alignment even though the data is noncached. However, if the noncached option is /// specified when opening a volume, buffer alignment is enforced regardless of the file system on the volume. It is recommended on /// all file systems that you open volume handles as noncached, and follow the noncached I/O restrictions. /// /// /// Note To read or write to the last few sectors of the volume, you must call DeviceIoControl and specify /// FSCTL_ALLOW_EXTENDED_DASD_IO. This signals the file system driver not to perform any I/O boundary checks on partition read or /// write calls. Instead, boundary checks are performed by the device driver. /// /// Changer Device /// /// The IOCTL_CHANGER_* control codes for DeviceIoControl accept a handle to a changer device. To open a changer device, use a /// file name of the following form: "\\.\Changerx" where x is a number that indicates which device to open, starting with zero. To /// open changer device zero in an application that is written in C or C++, use the following file name: "\\\\.\\Changer0". /// /// Tape Drives /// /// You can open tape drives by using a file name of the following form: "\\.\TAPEx" where x is a number that indicates which drive /// to open, starting with tape drive zero. To open tape drive zero in an application that is written in C or C++, use the following /// file name: "\\\\.\\TAPE0". /// /// For more information, see Backup. /// Communications Resources /// /// The CreateFile2 function can create a handle to a communications resource, such as the serial port COM1. For /// communications resources, the dwCreationDisposition parameter must be OPEN_EXISTING, the dwShareMode parameter must be /// zero (exclusive access), and the hTemplateFile parameter must be NULL. Read, write, or read/write access can be specified, /// and the handle can be opened for overlapped I/O. /// /// /// To specify a COM port number greater than 9, use the following syntax: "\.\COM10". This syntax works for all port numbers and /// hardware that allows COM port numbers to be specified. /// /// For more information about communications, see Communications. /// Consoles /// /// The CreateFile2 function can create a handle to console input (CONIN$). If the process has an open handle to it as a /// result of inheritance or duplication, it can also create a handle to the active screen buffer (CONOUT$). The calling process must /// be attached to an inherited console or one allocated by the AllocConsole function. For console handles, set the /// CreateFile2 parameters as follows. /// /// /// /// Parameters /// Value /// /// /// lpFileName /// /// Use the CONIN$ value to specify console input. Use the CONOUT$ value to specify console output. CONIN$ gets a handle to the /// console input buffer, even if the SetStdHandle function redirects the standard input handle. To get the standard input handle, /// use the GetStdHandlefunction. CONOUT$ gets a handle to the active screen buffer, even if SetStdHandleredirects the standard /// output handle. To get the standard output handle, use GetStdHandle. /// /// /// /// dwDesiredAccess /// is preferred, but either one can limit access. /// /// /// dwShareMode /// /// When opening CONIN$, specify FILE_SHARE_READ. When opening CONOUT$, specify FILE_SHARE_WRITE. If the calling process inherits the /// console, or if a child process should be able to access the console, this parameter must be . /// /// /// /// dwCreationDisposition /// You should specify OPEN_EXISTING when using CreateFile2 to open the console. /// /// /// Set the members of the CREATEFILE2_EXTENDED_PARAMETERS structure passed in the pCreateExParams parameter as follows. /// /// /// Members /// Value /// /// /// lpSecurityAttributes /// If you want the console to be inherited, the bInheritHandle member of the SECURITY_ATTRIBUTES structure must be TRUE. /// /// /// dwFileAttributes dwFileFlags dwSecurityQosFlags hTemplateFile /// Ignored. /// /// /// The following table shows various settings of dwDesiredAccess and lpFileName. /// /// /// lpFileName /// dwDesiredAccess /// Result /// /// /// "CON" /// GENERIC_READ /// Opens console for input. /// /// /// "CON" /// GENERIC_WRITE /// Opens console for output. /// /// /// "CON" /// /// Causes CreateFile2 to fail; GetLastError returns ERROR_FILE_NOT_FOUND. /// /// /// Mailslots /// /// If CreateFile2 opens the client end of a mailslot, the function returns INVALID_HANDLE_VALUE if the mailslot client /// attempts to open a local mailslot before the mailslot server has created it with the CreateMailSlot function. /// /// For more information, see Mailslots. /// Pipes /// /// If CreateFile2 opens the client end of a named pipe, the function uses any instance of the named pipe that is in the /// listening state. The opening process can duplicate the handle as many times as required, but after it is opened, the named pipe /// instance cannot be opened by another client. The access that is specified when a pipe is opened must be compatible with the /// access that is specified in the dwOpenModeparameter of the CreateNamedPipe function. /// /// /// If the CreateNamedPipe function was not successfully called on the server prior to this operation, a pipe will not exist and /// CreateFile2 will fail with ERROR_FILE_NOT_FOUND. /// /// /// If there is at least one active pipe instance but there are no available listener pipes on the server, which means all pipe /// instances are currently connected, CreateFile2 fails with ERROR_PIPE_BUSY. /// /// For more information, see Pipes. /// // https://docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-createfile2 HANDLE CreateFile2( LPCWSTR lpFileName, DWORD // dwDesiredAccess, DWORD dwShareMode, DWORD dwCreationDisposition, LPCREATEFILE2_EXTENDED_PARAMETERS pCreateExParams ); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("fileapi.h", MSDNShortId = "cd7a81f3-60ee-443a-99f3-a4c8afd365e7")] public static extern SafeHFILE CreateFile2([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, FileAccess dwDesiredAccess, FileShare dwShareMode, FileMode dwCreationDisposition, in CREATEFILE2_EXTENDED_PARAMETERS pCreateExParams); /// /// /// Creates or opens a file or I/O device. The most commonly used I/O devices are as follows: file, file stream, directory, physical /// disk, volume, console buffer, tape drive, communications resource, mailslot, and pipe. The function returns a handle that can be /// used to access the file or device for various types of I/O depending on the file or device and the flags and attributes specified. /// /// /// When called from a Windows Store app, CreateFile2 is simplified. You can open only files or directories inside the /// ApplicationData.LocalFolder or Package.InstalledLocation directories. You can't open named pipes or mailslots or create encrypted /// files ( FILE_ATTRIBUTE_ENCRYPTED). /// /// /// Note We refer here to the app's local folder and the package's installed location, not additional packages in the package /// graph, like resource packages. CreateFile2 doesn't support opening files in additional packages in the package graph. For /// example, suppose an app has a dependency on WinJS. The app can call CreateFile2 to open a file in its package but not in /// the WinJS package. /// /// /// To perform this operation as a transacted operation, which results in a handle that can be used for transacted I/O, use the /// CreateFileTransacted function. /// /// /// /// The name of the file or device to be created or opened. /// For information on special device names, see Defining an MS-DOS Device Name. /// /// To create a file stream, specify the name of the file, a colon, and then the name of the stream. For more information, see File Streams. /// /// /// Tip Starting with Windows 10, version 1607, you can opt-in to remove the MAX_PATH limitation without prepending /// "\\?\". See the "Maximum Path Length Limitation" section of Naming Files, Paths, and Namespaces for details. /// /// /// /// The requested access to the file or device, which can be summarized as read, write, both or neither zero). /// /// The most commonly used values are GENERIC_READ, GENERIC_WRITE, or both (). For more information, see Generic Access /// Rights, File Security and Access Rights, File Access Rights Constants, and ACCESS_MASK. /// /// /// If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes without /// accessing that file or device, even if GENERIC_READ access would have been denied. /// /// /// You cannot request an access mode that conflicts with the sharing mode that is specified by the dwShareMode parameter in an open /// request that already has an open handle. /// /// For more information, see the Remarks section of this topic and Creating and Opening Files. /// /// /// /// The requested sharing mode of the file or device, which can be read, write, both, delete, all of these, or none (refer to the /// following table). Access requests to attributes or extended attributes are not affected by this flag. /// /// /// If this parameter is zero and CreateFile2 succeeds, the file or device cannot be shared and cannot be opened again until /// the handle to the file or device is closed. For more information, see the Remarks section. /// /// /// You cannot request a sharing mode that conflicts with the access mode that is specified in an existing request that has an open /// handle. CreateFile2 would fail and the GetLastError function would return ERROR_SHARING_VIOLATION. /// /// /// To enable a process to share a file or device while another process has the file or device open, use a compatible combination of /// one or more of the following values. For more information about valid combinations of this parameter with the dwDesiredAccess /// parameter, see Creating and Opening Files. /// /// /// Note The sharing options for each open handle remain in effect until that handle is closed, regardless of process context. /// /// /// /// Value /// Meaning /// /// /// 0 0x00000000 /// /// Prevents other processes from opening a file or device if they request delete, read, or write access. Exclusive access to a file /// or directory is only granted if the application has write access to the file. /// /// /// /// FILE_SHARE_DELETE 0x00000004 /// /// Enables subsequent open operations on a file or device to request delete access. Otherwise, other processes cannot open the file /// or device if they request delete access. If this flag is not specified, but the file or device has been opened for delete access, /// the function fails. /// /// /// /// FILE_SHARE_READ 0x00000001 /// /// Enables subsequent open operations on a file or device to request read access. Otherwise, other processes cannot open the file or /// device if they request read access. If this flag is not specified, but the file or device has been opened for read access, the /// function fails. If a file or directory is being opened and this flag is not specified, and the caller does not have write access /// to the file or directory, the function fails. /// /// /// /// FILE_SHARE_WRITE 0x00000002 /// /// Enables subsequent open operations on a file or device to request write access. Otherwise, other processes cannot open the file /// or device if they request write access. If this flag is not specified, but the file or device has been opened for write access or /// has a file mapping with write access, the function fails. /// /// /// /// /// /// An action to take on a file or device that exists or does not exist. /// For devices other than files, this parameter is usually set to OPEN_EXISTING. /// For more information, see the Remarks section. /// This parameter must be one of the following values, which cannot be combined: /// /// /// Value /// Meaning /// /// /// CREATE_ALWAYS 2 /// /// Creates a new file, always. If the specified file exists and is writable, the function overwrites the file, the function /// succeeds, and last-error code is set to ERROR_ALREADY_EXISTS (183). If the specified file does not exist and is a valid path, a /// new file is created, the function succeeds, and the last-error code is set to zero. For more information, see the Remarks section /// of this topic. /// /// /// /// CREATE_NEW 1 /// /// Creates a new file, only if it does not already exist. If the specified file exists, the function fails and the last-error code /// is set to ERROR_FILE_EXISTS (80). If the specified file does not exist and is a valid path to a writable location, a new file is created. /// /// /// /// OPEN_ALWAYS 4 /// /// Opens a file, always. If the specified file exists, the function succeeds and the last-error code is set to ERROR_ALREADY_EXISTS /// (183). If the specified file does not exist and is a valid path to a writable location, the function creates a file and the /// last-error code is set to zero. /// /// /// /// OPEN_EXISTING 3 /// /// Opens a file or device, only if it exists. If the specified file or device does not exist, the function fails and the last-error /// code is set to ERROR_FILE_NOT_FOUND (2). For more information about devices, see the Remarks section. /// /// /// /// TRUNCATE_EXISTING 5 /// /// Opens a file and truncates it so that its size is zero bytes, only if it exists. If the specified file does not exist, the /// function fails and the last-error code is set to ERROR_FILE_NOT_FOUND (2). The calling process must open the file with the /// GENERIC_WRITE bit set as part of the dwDesiredAccess parameter. /// /// /// /// /// Pointer to an optional CREATEFILE2_EXTENDED_PARAMETERS structure. /// /// If the function succeeds, the return value is an open handle to the specified file, device, named pipe, or mail slot. /// If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call GetLastError. /// /// /// /// To compile an application that uses the CreateFile2 function, define the _WIN32_WINNT macro as 0x0602 or later. For /// more information, see Using the Windows Headers. /// /// /// CreateFile2 supports file interaction and most other types of I/O devices and mechanisms available to Windows developers. /// This section attempts to cover the varied issues developers may experience when using CreateFile2 in different contexts /// and with different I/O types. The text attempts to use the word file only when referring specifically to data stored in an actual /// file on a file system. However, some uses of file may be referring more generally to an I/O object that supports file-like /// mechanisms. This liberal use of the term file is particularly prevalent in constant names and parameter names because of the /// previously mentioned historical reasons. /// /// /// When an application is finished using the object handle returned by CreateFile2, use the CloseHandle function to close the /// handle. This not only frees up system resources, but can have wider influence on things like sharing the file or device and /// committing data to disk. Specifics are noted within this topic as appropriate. /// /// /// Some file systems, such as the NTFS file system, support compression or encryption for individual files and directories. On /// volumes that have a mounted file system with this support, a new file inherits the compression and encryption attributes of its directory. /// /// /// You cannot use CreateFile2 to control compression, decompression, or decryption on a file or directory. For more /// information, see Creating and Opening Files, File Compression and Decompression, and File Encryption. /// /// /// If the lpSecurityAttributes member of the CREATEFILE2_EXTENDED_PARAMETERS structure passed in the pCreateExParams /// parameter is NULL, the handle returned by CreateFile2 cannot be inherited by any child processes your application /// may create. The following information regarding this member also applies: /// /// /// /// /// If the bInheritHandle member variable is not FALSE, which is any nonzero value, then the handle can be inherited. /// Therefore it is critical this structure member be properly initialized to FALSE if you do not intend the handle to be inheritable. /// /// /// /// /// The access control lists (ACL) in the default security descriptor for a file or directory are inherited from its parent directory. /// /// /// /// /// The target file system must support security on files and directories for the lpSecurityDescriptor member to have an /// effect on them, which can be determined by using GetVolumeInformation. /// /// /// /// In Windows 8 and Windows Server 2012, this function is supported by the following technologies. /// /// /// Technology /// Supported /// /// /// Server Message Block (SMB) 3.0 protocol /// Yes /// /// /// SMB 3.0 Transparent Failover (TFO) /// No /// /// /// SMB 3.0 with Scale-out File Shares (SO) /// No /// /// /// Cluster Shared Volume File System (CsvFS) /// Yes /// /// /// Resilient File System (ReFS) /// Yes /// /// /// Symbolic Link Behavior /// /// If the call to this function creates a file, there is no change in behavior. Also, consider the following information regarding /// FILE_FLAG_OPEN_REPARSE_POINT flag for the dwFileFlags member of the CREATEFILE2_EXTENDED_PARAMETERS structure /// passed in the pCreateExParams parameter: /// /// /// /// If FILE_FLAG_OPEN_REPARSE_POINT is specified: /// /// /// If FILE_FLAG_OPEN_REPARSE_POINT is not specified: /// /// /// Files /// /// If you rename or delete a file and then restore it shortly afterward, the system searches the cache for file information to /// restore. Cached information includes its short/long name pair and creation time. /// /// /// If you call CreateFile2 on a file that is pending deletion as a result of a previous call to DeleteFile, the function /// fails. The operating system delays file deletion until all handles to the file are closed. GetLastError returns ERROR_ACCESS_DENIED. /// /// /// The dwDesiredAccess parameter can be zero, allowing the application to query file attributes without accessing the file if the /// application is running with adequate security settings. This is useful to test for the existence of a file without opening it for /// read and/or write access, or to obtain other statistics about the file or directory. See Obtaining and Setting File Information /// and GetFileInformationByHandle. /// /// /// When an application creates a file across a network, it is better to use for dwDesiredAccess than to use GENERIC_WRITE /// alone. The resulting code is faster, because the redirector can use the cache manager and send fewer SMBs with more data. This /// combination also avoids an issue where writing to a file across a network can occasionally return ERROR_ACCESS_DENIED. /// /// For more information, see Creating and Opening Files. /// File Streams /// /// On NTFS file systems, you can use CreateFile2 to create separate streams within a file. For more information, see File Streams. /// /// Directories /// /// An application cannot create a directory by using CreateFile2, therefore only the OPEN_EXISTING value is valid for /// dwCreationDisposition for this use case. To create a directory, the application must call CreateDirectory or CreateDirectoryEx. /// /// /// To open a directory using CreateFile2, specify the FILE_FLAG_BACKUP_SEMANTICS flag as part of dwFileFlags /// member of the CREATEFILE2_EXTENDED_PARAMETERS structure passed in the pCreateExParams parameter. Appropriate security checks /// still apply when this flag is used without SE_BACKUP_NAME and SE_RESTORE_NAME privileges. /// /// /// When using CreateFile2 to open a directory during defragmentation of a FAT or FAT32 file system volume, do not specify the /// MAXIMUM_ALLOWED access right. Access to the directory is denied if this is done. Specify the GENERIC_READ access /// right instead. /// /// For more information, see About Directory Management. /// Physical Disks and Volumes /// /// Direct access to the disk or to a volume is restricted. For more information, see "Changes to the file system and to the storage /// stack to restrict direct disk access and direct volume access in Windows Vista and in Windows Server 2008" in the Help and /// Support Knowledge Base at http://support.microsoft.com/kb/942448. /// /// /// You can use the CreateFile2 function to open a physical disk drive or a volume, which returns a direct access storage /// device (DASD) handle that can be used with the DeviceIoControl function. This enables you to access the disk or volume directly, /// for example such disk metadata as the partition table. However, this type of access also exposes the disk drive or volume to /// potential data loss, because an incorrect write to a disk using this mechanism could make its contents inaccessible to the /// operating system. To ensure data integrity, be sure to become familiar with DeviceIoControl and how other APIs behave /// differently with a direct access handle as opposed to a file system handle. /// /// The following requirements must be met for such a call to succeed: /// /// /// The caller must have administrative privileges. For more information, see Running with Special Privileges. /// /// /// The dwCreationDisposition parameter must have the OPEN_EXISTING flag. /// /// /// When opening a volume or floppy disk, the dwShareMode parameter must have the FILE_SHARE_WRITE flag. /// /// /// /// Note The dwDesiredAccess parameter can be zero, allowing the application to query device attributes without accessing a /// device. This is useful for an application to determine the size of a floppy disk drive and the formats it supports without /// requiring a floppy disk in a drive, for instance. It can also be used for reading statistics without requiring higher-level data /// read/write permission. /// /// /// When opening a physical drive x:, the lpFileName string should be the following form: "\\.\PhysicalDriveX". Hard disk numbers /// start at zero. The following table shows some examples of physical drive strings. /// /// /// /// String /// Meaning /// /// /// "\\.\PhysicalDrive0" /// Opens the first physical drive. /// /// /// "\\.\PhysicalDrive2" /// Opens the third physical drive. /// /// /// /// To obtain the physical drive identifier for a volume, open a handle to the volume and call the DeviceIoControl function with /// IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS. This control code returns the disk number and offset for each of the volume's one or more /// extents; a volume can span multiple physical disks. /// /// For an example of opening a physical drive, see Calling DeviceIoControl. /// /// When opening a volume or removable media drive (for example, a floppy disk drive or flash memory thumb drive), the lpFileName /// string should be the following form: "\.<i>X:". Do not use a trailing backslash (), which indicates the root directory of a /// drive. The following table shows some examples of drive strings. /// /// /// /// String /// Meaning /// /// /// "\\.\A:" /// Opens floppy disk drive A. /// /// /// "\\.\C:" /// Opens the C: volume. /// /// /// "\\.\C:\" /// Opens the file system of the C: volume. /// /// /// You can also open a volume by referring to its volume name. For more information, see Naming a Volume. /// /// A volume contains one or more mounted file systems. Volume handles can be opened as noncached at the discretion of the particular /// file system, even when the noncached option is not specified in CreateFile2. You should assume that all Microsoft file /// systems open volume handles as noncached. The restrictions on noncached I/O for files also apply to volumes. /// /// /// A file system may or may not require buffer alignment even though the data is noncached. However, if the noncached option is /// specified when opening a volume, buffer alignment is enforced regardless of the file system on the volume. It is recommended on /// all file systems that you open volume handles as noncached, and follow the noncached I/O restrictions. /// /// /// Note To read or write to the last few sectors of the volume, you must call DeviceIoControl and specify /// FSCTL_ALLOW_EXTENDED_DASD_IO. This signals the file system driver not to perform any I/O boundary checks on partition read or /// write calls. Instead, boundary checks are performed by the device driver. /// /// Changer Device /// /// The IOCTL_CHANGER_* control codes for DeviceIoControl accept a handle to a changer device. To open a changer device, use a /// file name of the following form: "\\.\Changerx" where x is a number that indicates which device to open, starting with zero. To /// open changer device zero in an application that is written in C or C++, use the following file name: "\\\\.\\Changer0". /// /// Tape Drives /// /// You can open tape drives by using a file name of the following form: "\\.\TAPEx" where x is a number that indicates which drive /// to open, starting with tape drive zero. To open tape drive zero in an application that is written in C or C++, use the following /// file name: "\\\\.\\TAPE0". /// /// For more information, see Backup. /// Communications Resources /// /// The CreateFile2 function can create a handle to a communications resource, such as the serial port COM1. For /// communications resources, the dwCreationDisposition parameter must be OPEN_EXISTING, the dwShareMode parameter must be /// zero (exclusive access), and the hTemplateFile parameter must be NULL. Read, write, or read/write access can be specified, /// and the handle can be opened for overlapped I/O. /// /// /// To specify a COM port number greater than 9, use the following syntax: "\.\COM10". This syntax works for all port numbers and /// hardware that allows COM port numbers to be specified. /// /// For more information about communications, see Communications. /// Consoles /// /// The CreateFile2 function can create a handle to console input (CONIN$). If the process has an open handle to it as a /// result of inheritance or duplication, it can also create a handle to the active screen buffer (CONOUT$). The calling process must /// be attached to an inherited console or one allocated by the AllocConsole function. For console handles, set the /// CreateFile2 parameters as follows. /// /// /// /// Parameters /// Value /// /// /// lpFileName /// /// Use the CONIN$ value to specify console input. Use the CONOUT$ value to specify console output. CONIN$ gets a handle to the /// console input buffer, even if the SetStdHandle function redirects the standard input handle. To get the standard input handle, /// use the GetStdHandlefunction. CONOUT$ gets a handle to the active screen buffer, even if SetStdHandleredirects the standard /// output handle. To get the standard output handle, use GetStdHandle. /// /// /// /// dwDesiredAccess /// is preferred, but either one can limit access. /// /// /// dwShareMode /// /// When opening CONIN$, specify FILE_SHARE_READ. When opening CONOUT$, specify FILE_SHARE_WRITE. If the calling process inherits the /// console, or if a child process should be able to access the console, this parameter must be . /// /// /// /// dwCreationDisposition /// You should specify OPEN_EXISTING when using CreateFile2 to open the console. /// /// /// Set the members of the CREATEFILE2_EXTENDED_PARAMETERS structure passed in the pCreateExParams parameter as follows. /// /// /// Members /// Value /// /// /// lpSecurityAttributes /// If you want the console to be inherited, the bInheritHandle member of the SECURITY_ATTRIBUTES structure must be TRUE. /// /// /// dwFileAttributes dwFileFlags dwSecurityQosFlags hTemplateFile /// Ignored. /// /// /// The following table shows various settings of dwDesiredAccess and lpFileName. /// /// /// lpFileName /// dwDesiredAccess /// Result /// /// /// "CON" /// GENERIC_READ /// Opens console for input. /// /// /// "CON" /// GENERIC_WRITE /// Opens console for output. /// /// /// "CON" /// /// Causes CreateFile2 to fail; GetLastError returns ERROR_FILE_NOT_FOUND. /// /// /// Mailslots /// /// If CreateFile2 opens the client end of a mailslot, the function returns INVALID_HANDLE_VALUE if the mailslot client /// attempts to open a local mailslot before the mailslot server has created it with the CreateMailSlot function. /// /// For more information, see Mailslots. /// Pipes /// /// If CreateFile2 opens the client end of a named pipe, the function uses any instance of the named pipe that is in the /// listening state. The opening process can duplicate the handle as many times as required, but after it is opened, the named pipe /// instance cannot be opened by another client. The access that is specified when a pipe is opened must be compatible with the /// access that is specified in the dwOpenModeparameter of the CreateNamedPipe function. /// /// /// If the CreateNamedPipe function was not successfully called on the server prior to this operation, a pipe will not exist and /// CreateFile2 will fail with ERROR_FILE_NOT_FOUND. /// /// /// If there is at least one active pipe instance but there are no available listener pipes on the server, which means all pipe /// instances are currently connected, CreateFile2 fails with ERROR_PIPE_BUSY. /// /// For more information, see Pipes. /// // https://docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-createfile2 HANDLE CreateFile2( LPCWSTR lpFileName, DWORD // dwDesiredAccess, DWORD dwShareMode, DWORD dwCreationDisposition, LPCREATEFILE2_EXTENDED_PARAMETERS pCreateExParams ); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("fileapi.h", MSDNShortId = "cd7a81f3-60ee-443a-99f3-a4c8afd365e7")] public static extern SafeHFILE CreateFile2([MarshalAs(UnmanagedType.LPWStr)] string lpFileName, FileAccess dwDesiredAccess, FileShare dwShareMode, FileMode dwCreationDisposition, [Optional] IntPtr pCreateExParams); /// Defines, redefines, or deletes MS-DOS device names. /// /// The controllable aspects of the DefineDosDevice function. This parameter can be one or more of the following values. /// /// /// Value /// Meaning /// /// /// DDD_EXACT_MATCH_ON_REMOVE 0x00000004 /// /// If this value is specified along with DDD_REMOVE_DEFINITION, the function will use an exact match to determine which mapping to /// remove. Use this value to ensure that you do not delete something that you did not define. /// /// /// /// DDD_NO_BROADCAST_SYSTEM 0x00000008 /// /// Do not broadcast the WM_SETTINGCHANGE message. By default, this message is broadcast to notify the shell and applications of the change. /// /// /// /// DDD_RAW_TARGET_PATH 0x00000001 /// Uses the lpTargetPath string as is. Otherwise, it is converted from an MS-DOS path to a path. /// /// /// DDD_REMOVE_DEFINITION 0x00000002 /// /// Removes the specified definition for the specified device. To determine which definition to remove, the function walks the list /// of mappings for the device, looking for a match of lpTargetPath against a prefix of each mapping associated with this device. The /// first mapping that matches is the one removed, and then the function returns. If lpTargetPath is NULL or a pointer to a NULL /// string, the function will remove the first mapping associated with the device and pop the most recent one pushed. If there is /// nothing left to pop, the device name will be removed. If this value is not specified, the string pointed to by the lpTargetPath /// parameter will become the new mapping for this device. /// /// /// /// /// /// A pointer to an MS-DOS device name string specifying the device the function is defining, redefining, or deleting. The device /// name string must not have a colon as the last character, unless a drive letter is being defined, redefined, or deleted. For /// example, drive C would be the string "C:". In no case is a trailing backslash ("") allowed. /// /// /// A pointer to a path string that will implement this device. The string is an MS-DOS path string unless the /// DDD_RAW_TARGET_PATH flag is specified, in which case this string is a path string. /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// /// /// /// MS-DOS device names are stored as junctions in the object namespace. The code that converts an MS-DOS path into a corresponding /// path uses these junctions to map MS-DOS devices and drive letters. The DefineDosDevice function enables an application to /// modify the junctions used to implement the MS-DOS device namespace. /// /// /// To retrieve the current mapping for a particular MS-DOS device name or to obtain a list of all MS-DOS devices known to the /// system, use the QueryDosDevice function. /// /// /// To define a drive letter assignment that is persistent across boots and not a network share, use the SetVolumeMountPoint /// function. If the volume to be mounted already has a drive letter assigned to it, use the DeleteVolumeMountPoint function to /// remove the assignment. /// /// /// Drive letters and device names defined at system boot time are protected from redefinition and deletion unless the user is an administrator. /// /// /// Starting with Windows XP, this function creates a device name for a caller that is not running in the "LocalSystem" context in /// its own Local MS-DOS device namespace. If the caller is running in the "LocalSystem" context, the function creates the device /// name in the Global MS-DOS device namespace. For more information, see Defining an MS DOS Device Name and File Names, Paths, and Namespaces. /// /// In Windows 8 and Windows Server 2012, this function is supported by the following technologies. /// /// /// Technology /// Supported /// /// /// Server Message Block (SMB) 3.0 protocol /// No /// /// /// SMB 3.0 Transparent Failover (TFO) /// No /// /// /// SMB 3.0 with Scale-out File Shares (SO) /// No /// /// /// Cluster Shared Volume File System (CsvFS) /// No /// /// /// Resilient File System (ReFS) /// No /// /// /// /// SMB does not support volume management functions. For CsvFs, a new name will not be replicated to the other nodes on the cluster. /// /// Examples /// For an example, see Editing Drive Letter Assignments. /// // https://docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-definedosdevicew BOOL DefineDosDeviceW( DWORD dwFlags, // LPCWSTR lpDeviceName, LPCWSTR lpTargetPath ); [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [PInvokeData("fileapi.h", MSDNShortId = "924b1456-b2c5-4d52-aacf-6172608c73ea")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool DefineDosDevice(DDD dwFlags, string lpDeviceName, string lpTargetPath); /// Deletes an existing file. /// The name of the file to be deleted. /// /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero.To get extended error /// information, call GetLastError. /// [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [PInvokeData("FileAPI.h", MSDNShortId = "aa363915")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool DeleteFile(string lpFileName); /// Deletes a drive letter or mounted folder. /// /// The drive letter or mounted folder to be deleted. A trailing backslash is required, for example, "X:\" or "Y:\MountX\". /// /// /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero.To get extended error /// information, call GetLastError. /// [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [PInvokeData("FileAPI.h", MSDNShortId = "aa363927")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool DeleteVolumeMountPoint(string lpszVolumeMountPoint); /// Ends an asynchronous request for ReadFile. /// An IAsyncResult instance returned by a call to the BeginReadFile method. public static void EndReadFile(IAsyncResult asyncResult) => OverlappedAsync.EndOverlappedFunction(asyncResult); /// Ends an asynchronous request for WriteFile. /// An IAsyncResult instance returned by a call to the BeginWriteFile method. public static void EndWriteFile(IAsyncResult asyncResult) => OverlappedAsync.EndOverlappedFunction(asyncResult); /// /// Searches a directory for a file or subdirectory with a name that matches a specific name (or partial name if wildcards are used). /// /// /// The directory or path, and the file name. The file name can include wildcard characters, for example, an asterisk (*) or a /// question mark (?). /// /// This parameter should not be NULL, an invalid string (for example, an empty string or a string that is missing the terminating /// null character), or end in a trailing backslash (\). /// /// /// If the string ends with a wildcard, period (.), or directory name, the user must have access permissions to the root and all /// subdirectories on the path. /// /// /// The type of filtering to perform that is different from wildcard matching. /// /// Specifies additional flags that control the search. /// /// /// Value /// Meaning /// /// /// FIND_FIRST_EX_CASE_SENSITIVE 1 /// Searches are case-sensitive. /// /// /// FIND_FIRST_EX_LARGE_FETCH 2 /// /// Uses a larger buffer for directory queries, which can increase performance of the find operation. Windows Server 2008, Windows /// Vista, Windows Server 2003 and Windows XP: This value is not supported until Windows Server 2008 R2 and Windows 7. /// /// /// /// FIND_FIRST_EX_ON_DISK_ENTRIES_ONLY 4 /// /// Limits the results to files that are physically on disk. This flag is only relevant when a file virtualization filter is present. /// /// /// /// /// /// If , the function does not query the short file name, improving overall enumeration speed, and the /// cAlternateFileName member of the WIN32_FIND_DATA result is always a NULL string. /// /// Windows Server 2008, Windows Vista, Windows Server 2003 and Windows XP: This value is not supported until Windows Server /// 2008 R2 and Windows 7. /// /// /// An enumeration of WIN32_FIND_DATA structures that contain information about the found files or directories. public static IEnumerable EnumFilesEx(string lpFileName, FINDEX_SEARCH_OPS fSearchOp = FINDEX_SEARCH_OPS.FindExSearchNameMatch, FIND_FIRST dwAdditionalFlags = 0, bool excludeShortName = false) { var minWin7 = Environment.OSVersion.Version >= new Version(6, 1); var lvl = excludeShortName && minWin7 ? FINDEX_INFO_LEVELS.FindExInfoBasic : FINDEX_INFO_LEVELS.FindExInfoStandard; using (var h = FindFirstFileEx(lpFileName, lvl, out var data, fSearchOp, default, dwAdditionalFlags)) { if (h.IsInvalid) ThrowIfNotNoMore(); yield return data; while (FindNextFile(h, out data)) yield return data; ThrowIfNotNoMore(); } void ThrowIfNotNoMore() { var e = Win32Error.GetLastError(); if (e.Failed && e != Win32Error.ERROR_NO_MORE_FILES) throw e.GetException(); } } /// Retrieves the names of the volumes on a computer using and . /// An enumeration of the volume names. public static IEnumerable EnumVolumes() { var sb = new StringBuilder(MAX_PATH, MAX_PATH); using (var h = FindFirstVolume(sb, (uint)sb.Capacity)) { if (h.IsInvalid) ThrowIfNotNoMore(); yield return sb.ToString(); while (FindNextVolume(h, sb, (uint)sb.Capacity)) yield return sb.ToString(); ThrowIfNotNoMore(); } void ThrowIfNotNoMore() { var e = Win32Error.GetLastError(); if (e.Failed && e != Win32Error.ERROR_NO_MORE_FILES) throw e.GetException(); } } /// Converts a file time to a local file time. /// /// A pointer to a FILETIME structure containing the UTC-based file time to be converted into a local file time. /// /// /// A pointer to a FILETIME structure to receive the converted local file time. This parameter cannot be the same as the lpFileTime parameter. /// /// /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero.To get extended error /// information, call GetLastError. /// [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("FileAPI.h", MSDNShortId = "ms724277")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool FileTimeToLocalFileTime(in FILETIME lpFileTime, out FILETIME lpLocalFileTime); /// /// Closes a file search handle opened by the FindFirstFile, FindFirstFileEx, FindFirstFileNameW, FindFirstFileNameTransactedW, /// FindFirstFileTransacted, FindFirstStreamTransactedW, or FindFirstStreamW functions. /// /// The file search handle. /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// /// /// /// After the FindClose function is called, the handle specified by the hFindFile parameter cannot be used in subsequent calls /// to the FindNextFile, FindNextFileNameW, FindNextStreamW, or FindClose functions. /// /// In Windows 8 and Windows Server 2012, this function is supported by the following technologies. /// /// /// Technology /// Supported /// /// /// Server Message Block (SMB) 3.0 protocol /// Yes /// /// /// SMB 3.0 Transparent Failover (TFO) /// Yes /// /// /// SMB 3.0 with Scale-out File Shares (SO) /// Yes /// /// /// Cluster Shared Volume File System (CsvFS) /// Yes /// /// /// Resilient File System (ReFS) /// Yes /// /// /// Examples /// For an example, see Listing the Files in a Directory. /// // https://docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-findclose BOOL FindClose( HANDLE hFindFile ); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("fileapi.h", MSDNShortId = "64b3bc49-1e0e-4572-9d9f-936c45f5b01c")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool FindClose([In] IntPtr hFindFile); /// Stops change notification handle monitoring. /// A handle to a change notification handle created by the FindFirstChangeNotification function. /// /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero.To get extended error /// information, call GetLastError. /// [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("FileAPI.h", MSDNShortId = "aa364414")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool FindCloseChangeNotification([In] IntPtr hChangeHandle); /// /// Creates a change notification handle and sets up initial change notification filter conditions. A wait on a notification handle /// succeeds when a change matching the filter conditions occurs in the specified directory or subtree. The function does not report /// changes to the specified directory itself. /// /// This function does not indicate the change that satisfied the wait condition.To retrieve information about the specific change as /// part of the notification, use the ReadDirectoryChangesW function. /// /// /// The full path of the directory to be watched. This cannot be a relative path or an empty string. /// /// If this parameter is TRUE, the function monitors the directory tree rooted at the specified directory; if it is FALSE, it /// monitors only the specified directory. /// /// The filter conditions that satisfy a change notification wait. /// /// If the function succeeds, the return value is a handle to a find change notification object. If the function fails, the return /// value is INVALID_HANDLE_VALUE.To get extended error information, call GetLastError. /// [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [PInvokeData("FileAPI.h", MSDNShortId = "aa364417")] public static extern SafeFindChangeNotificationHandle FindFirstChangeNotification( string lpPathName, [MarshalAs(UnmanagedType.Bool)] bool bWatchSubtree, FILE_NOTIFY_CHANGE dwNotifyFilter); /// /// Searches a directory for a file or subdirectory with a name that matches a specific name (or partial name if wildcards are used). /// /// /// The directory or path, and the file name. The file name can include wildcard characters, for example, an asterisk (*) or a /// question mark (?). /// /// This parameter should not be NULL, an invalid string (for example, an empty string or a string that is missing the terminating /// null character), or end in a trailing backslash (\). /// /// /// If the string ends with a wildcard, period (.), or directory name, the user must have access permissions to the root and all /// subdirectories on the path. /// /// /// A pointer to the WIN32_FIND_DATA structure that receives information about a found file or directory. /// /// If the function succeeds, the return value is a search handle used in a subsequent call to FindNextFile or FindClose, and the /// lpFindFileData parameter contains information about the first file or directory found. /// /// If the function fails or fails to locate files from the search string in the lpFileName parameter, the return value is /// INVALID_HANDLE_VALUE and the contents of lpFindFileData are indeterminate. To get extended error information, call the /// GetLastError function. /// /// If the function fails because no matching files can be found, the GetLastError function returns ERROR_FILE_NOT_FOUND. /// [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [PInvokeData("FileAPI.h", MSDNShortId = "aa364418")] public static extern SafeSearchHandle FindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData); /// /// Searches a directory for a file or subdirectory with a name and attributes that match those specified. /// For the most basic version of this function, see FindFirstFile. /// To perform this operation as a transacted operation, use the FindFirstFileTransacted function. /// /// /// /// The directory or path, and the file name. The file name can include wildcard characters, for example, an asterisk (*) or a /// question mark (?). /// /// /// This parameter should not be NULL, an invalid string (for example, an empty string or a string that is missing the /// terminating null character), or end in a trailing backslash (). /// /// /// If the string ends with a wildcard, period, or directory name, the user must have access to the root and all subdirectories on /// the path. /// /// /// In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to approximately /// 32,000 wide characters, call the Unicode version of the function ( FindFirstFileExW), and prepend "\?" to the path. For /// more information, see Naming a File. /// /// /// Tip Starting in Windows 10, version 1607, for the unicode version of this function ( FindFirstFileExW), you can /// opt-in to remove the MAX_PATH character limitation without prepending "\\?\". See the "Maximum Path Limitation" section of /// Naming Files, Paths, and Namespaces for details. /// /// /// /// The information level of the returned data. /// This parameter is one of the FINDEX_INFO_LEVELS enumeration values. /// /// /// A pointer to the buffer that receives the file data. /// The pointer type is determined by the level of information that is specified in the fInfoLevelId parameter. /// /// /// The type of filtering to perform that is different from wildcard matching. /// This parameter is one of the FINDEX_SEARCH_OPS enumeration values. /// /// /// A pointer to the search criteria if the specified fSearchOp needs structured search information. /// /// At this time, none of the supported fSearchOp values require extended search information. Therefore, this pointer must be NULL. /// /// /// /// Specifies additional flags that control the search. /// /// /// Value /// Meaning /// /// /// FIND_FIRST_EX_CASE_SENSITIVE 1 /// Searches are case-sensitive. /// /// /// FIND_FIRST_EX_LARGE_FETCH 2 /// /// Uses a larger buffer for directory queries, which can increase performance of the find operation. Windows Server 2008, Windows /// Vista, Windows Server 2003 and Windows XP: This value is not supported until Windows Server 2008 R2 and Windows 7. /// /// /// /// FIND_FIRST_EX_ON_DISK_ENTRIES_ONLY 4 /// /// Limits the results to files that are physically on disk. This flag is only relevant when a file virtualization filter is present. /// /// /// /// /// /// /// If the function succeeds, the return value is a search handle used in a subsequent call to FindNextFile or FindClose, and the /// lpFindFileData parameter contains information about the first file or directory found. /// /// /// If the function fails or fails to locate files from the search string in the lpFileName parameter, the return value is /// INVALID_HANDLE_VALUE and the contents of lpFindFileData are indeterminate. To get extended error information, call the /// GetLastError function. /// /// /// /// /// The FindFirstFileEx function opens a search handle and returns information about the first file that the file system finds /// with a name that matches the specified pattern. This may or may not be the first file or directory that appears in a /// directory-listing application (such as the dir command) when given the same file name string pattern. This is because /// FindFirstFileEx does no sorting of the search results. For additional information, see FindNextFile. /// /// The following list identifies some other search characteristics: /// /// /// The search is performed strictly on the name of the file, not on any attributes such as a date or a file type. /// /// /// The search includes the long and short file names. /// /// /// An attempt to open a search with a trailing backslash always fails. /// /// /// /// Passing an invalid string, NULL, or empty string for the lpFileName parameter is not a valid use of this function. Results /// in this case are undefined. /// /// /// /// /// Note In rare cases or on a heavily loaded system, file attribute information on NTFS file systems may not be current at /// the time this function is called. To be assured of getting the current NTFS file system file attributes, call the /// GetFileInformationByHandle function. /// /// /// If the underlying file system does not support the specified type of filtering, other than directory filtering, /// FindFirstFileEx fails with the error ERROR_NOT_SUPPORTED. The application must use FINDEX_SEARCH_OPS type /// FileExSearchNameMatch and perform its own filtering. /// /// /// After the search handle is established, use it in the FindNextFile function to search for other files that match the same pattern /// with the same filtering that is being performed. When the search handle is not needed, it should be closed by using the FindClose function. /// /// /// As stated previously, you cannot use a trailing backslash () in the lpFileName input string for FindFirstFileEx, therefore /// it may not be obvious how to search root directories. If you want to see files or get the attributes of a root directory, the /// following options would apply: /// /// /// /// To examine files in a root directory, you can use "C:\*" and step through the directory by using FindNextFile. /// /// /// To get the attributes of a root directory, use the GetFileAttributes function. /// /// /// Note Prepending the string "\\?\" does not allow access to the root directory. /// /// On network shares, you can use an lpFileName in the form of the following: "\\server\service\*". However, you cannot use an /// lpFileName that points to the share itself; for example, "\\server\service" is not valid. /// /// /// To examine a directory that is not a root directory, use the path to that directory, without a trailing backslash. For example, /// an argument of "C:\Windows" returns information about the directory "C:\Windows", not about a directory or file in "C:\Windows". /// To examine the files and directories in "C:\Windows", use an lpFileName of "C:\Windows*". /// /// The following call: /// Is equivalent to the following call: /// /// Be aware that some other thread or process could create or delete a file with this name between the time you query for the result /// and the time you act on the information. If this is a potential concern for your application, one possible solution is to use the /// CreateFile function with CREATE_NEW (which fails if the file exists) or OPEN_EXISTING (which fails if the file does /// not exist). /// /// /// If you are writing a 32-bit application to list all the files in a directory and the application may be run on a 64-bit computer, /// you should call Wow64DisableWow64FsRedirection before calling FindFirstFileEx and call Wow64RevertWow64FsRedirection after /// the last call to FindNextFile. For more information, see File System Redirector. /// /// /// If the path points to a symbolic link, the WIN32_FIND_DATA buffer contains information about the symbolic link, not the target. /// /// In Windows 8 and Windows Server 2012, this function is supported by the following technologies. /// /// /// Technology /// Supported /// /// /// Server Message Block (SMB) 3.0 protocol /// Yes /// /// /// SMB 3.0 Transparent Failover (TFO) /// Yes /// /// /// SMB 3.0 with Scale-out File Shares (SO) /// Yes /// /// /// Cluster Shared Volume File System (CsvFS) /// Yes /// /// /// Resilient File System (ReFS) /// Yes /// /// /// Examples /// /// The following code shows a minimal use of FindFirstFileEx. This program is equivalent to the example in the FindFirstFile topic. /// /// // https://docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-findfirstfileexa HANDLE FindFirstFileExA( LPCSTR // lpFileName, FINDEX_INFO_LEVELS fInfoLevelId, LPVOID lpFindFileData, FINDEX_SEARCH_OPS fSearchOp, LPVOID lpSearchFilter, DWORD // dwAdditionalFlags ); [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [PInvokeData("fileapi.h", MSDNShortId = "9f40e98f-153f-4b65-afd9-06742684c100")] public static extern SafeSearchHandle FindFirstFileEx(string lpFileName, FINDEX_INFO_LEVELS fInfoLevelId, out WIN32_FIND_DATA lpFindFileData, FINDEX_SEARCH_OPS fSearchOp, [Optional] IntPtr lpSearchFilter, FIND_FIRST dwAdditionalFlags); /// Retrieves the name of a volume on a computer. FindFirstVolume is used to begin scanning the volumes of a computer. /// /// A pointer to a buffer that receives a null-terminated string that specifies a volume GUID path for the first volume that is found. /// /// The length of the buffer to receive the volume GUID path, in TCHARs. /// /// If the function succeeds, the return value is a search handle used in a subsequent call to the FindNextVolume and FindVolumeClose functions. /// /// If the function fails to find any volumes, the return value is the INVALID_HANDLE_VALUE error code. To get extended error /// information, call GetLastError. /// /// [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [PInvokeData("FileAPI.h", MSDNShortId = "aa364419")] public static extern SafeVolumeSearchHandle FindFirstVolume([In, Out] StringBuilder lpszVolumeName, uint cchBufferLength); /// Requests that the operating system signal a change notification handle the next time it detects an appropriate change. /// A handle to a change notification handle created by the FindFirstChangeNotification function. /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// // BOOL WINAPI FindNextChangeNotification( _In_ HANDLE hChangeHandle); https://msdn.microsoft.com/en-us/library/windows/desktop/aa364427(v=vs.85).aspx [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("FileAPI.h", MSDNShortId = "aa364427")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool FindNextChangeNotification([In] SafeFindChangeNotificationHandle hChangeHandle); /// Continues a file search from a previous call to the FindFirstFile, FindFirstFileEx, or FindFirstFileTransacted functions. /// The search handle returned by a previous call to the FindFirstFile or FindFirstFileEx function. /// A pointer to the WIN32_FIND_DATA structure that receives information about the found file or subdirectory. /// /// If the function succeeds, the return value is nonzero and the lpFindFileData parameter contains information about the next file /// or directory found. /// /// If the function fails, the return value is zero and the contents of lpFindFileData are indeterminate. To get extended error /// information, call the GetLastError function. /// /// If the function fails because no more matching files can be found, the GetLastError function returns ERROR_NO_MORE_FILES. /// [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [PInvokeData("FileAPI.h", MSDNShortId = "aa364428")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool FindNextFile([In] SafeSearchHandle hFindFile, out WIN32_FIND_DATA lpFindFileData); /// /// Continues a volume search started by a call to the FindFirstVolume function. FindNextVolume finds one volume per call. /// /// The volume search handle returned by a previous call to the FindFirstVolume function. /// A pointer to a string that receives the volume GUID path that is found. /// The length of the buffer that receives the volume GUID path, in TCHARs. /// /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error /// information, call GetLastError. If no matching files can be found, the GetLastError function returns the ERROR_NO_MORE_FILES /// error code. In that case, close the search with the FindVolumeClose function. /// [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [PInvokeData("FileAPI.h", MSDNShortId = "aa364431")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool FindNextVolume(SafeVolumeSearchHandle hFindVolume, [In, Out] StringBuilder lpszVolumeName, uint cchBufferLength); /// /// Closes the specified volume search handle. The FindFirstVolume and FindNextVolume functions use this search handle to locate volumes. /// /// /// The volume search handle to be closed. This handle must have been previously opened by the FindFirstVolume function. /// /// /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero.To get extended error /// information, call GetLastError. /// [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("FileAPI.h", MSDNShortId = "aa364433")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool FindVolumeClose([In] IntPtr hFindVolume); /// Flushes the buffers of a specified file and causes all buffered data to be written to a file. /// /// A handle to the open file. /// The file handle must have the GENERIC_WRITE access right. For more information, see File Security and Access Rights. /// If hFile is a handle to a communications device, the function only flushes the transmit buffer. /// /// If hFile is a handle to the server end of a named pipe, the function does not return until the client has read all buffered data /// from the pipe. /// /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// /// The function fails if hFile is a handle to the console output. That is because the console output is not buffered. The function /// returns FALSE, and GetLastError returns ERROR_INVALID_HANDLE. /// /// [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("FileAPI.h", MSDNShortId = "aa364433")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool FlushFileBuffers([In] HFILE hFile); /// Retrieves information about the specified disk, including the amount of free space on the disk. /// /// The root directory of the disk for which information is to be returned. If this parameter is NULL, the function uses the root of /// the current disk. If this parameter is a UNC name, it must include a trailing backslash (for example, "\\MyServer\MyShare\"). /// Furthermore, a drive specification must have a trailing backslash (for example, "C:\"). The calling application must have /// FILE_LIST_DIRECTORY access rights for this directory. /// /// A pointer to a variable that receives the number of sectors per cluster. /// A pointer to a variable that receives the number of bytes per sector. /// /// A pointer to a variable that receives the total number of free clusters on the disk that are available to the user who is /// associated with the calling thread. /// If per-user disk quotas are in use, this value may be less than the total number of free clusters on the disk. /// /// /// A pointer to a variable that receives the total number of clusters on the disk that are available to the user who is associated /// with the calling thread. /// If per-user disk quotas are in use, this value may be less than the total number of clusters on the disk. /// /// /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero.To get extended error /// information, call GetLastError. /// [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] [PInvokeData("FileAPI.h", MSDNShortId = "aa364935")] public static extern bool GetDiskFreeSpace(string lpRootPathName, out uint lpSectorsPerCluster, out uint lpBytesPerSector, out uint lpNumberOfFreeClusters, out uint lpTotalNumberOfClusters); /// /// Retrieves information about the amount of space that is available on a disk volume, which is the total amount of space, the total /// amount of free space, and the total amount of free space available to the user that is associated with the calling thread. /// /// /// A directory on the disk. /// If this parameter is NULL, the function uses the root of the current disk. /// If this parameter is a UNC name, it must include a trailing backslash, for example, "\\MyServer\MyShare\". /// This parameter does not have to specify the root directory on a disk. The function accepts any directory on a disk. /// The calling application must have FILE_LIST_DIRECTORY access rights for this directory. /// /// /// A pointer to a variable that receives the total number of free bytes on a disk that are available to the user who is associated /// with the calling thread. /// This parameter can be NULL. /// If per-user quotas are being used, this value may be less than the total number of free bytes on a disk. /// /// /// A pointer to a variable that receives the total number of bytes on a disk that are available to the user who is associated with /// the calling thread. /// This parameter can be NULL. /// If per-user quotas are being used, this value may be less than the total number of bytes on a disk. /// To determine the total number of bytes on a disk or volume, use IOCTL_DISK_GET_LENGTH_INFO. /// /// /// A pointer to a variable that receives the total number of free bytes on a disk. /// This parameter can be NULL. /// /// /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero.To get extended error /// information, call GetLastError. /// [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] [PInvokeData("FileAPI.h", MSDNShortId = "aa364937")] public static extern bool GetDiskFreeSpaceEx(string lpDirectoryName, out ulong lpFreeBytesAvailable, out ulong lpTotalNumberOfBytes, out ulong lpTotalNumberOfFreeBytes); /// Determines whether a disk drive is a removable, fixed, CD-ROM, RAM disk, or network drive. /// /// The root directory for the drive. A trailing backslash is required.If this parameter is NULL, the function uses the root of the /// current directory. /// /// The return value specifies the type of drive, which can be one of the following values. [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [PInvokeData("FileAPI.h", MSDNShortId = "aa364937")] public static extern DRIVE_TYPE GetDriveType(string lpRootPathName); /// Retrieves file system attributes for a specified file or directory. /// The name of the file or directory. /// /// If the function succeeds, the return value contains the attributes of the specified file or directory. For a list of attribute /// values and their descriptions, see File Attribute Constants. If the function fails, the return value is /// INVALID_FILE_ATTRIBUTES.To get extended error information, call GetLastError. /// [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [PInvokeData("FileAPI.h", MSDNShortId = "aa364944")] public static extern FileFlagsAndAttributes GetFileAttributes(string lpFileName); /// Retrieves attributes for a specified file or directory. /// The name of the file or directory. /// A class of attribute information to retrieve. /// /// A pointer to a buffer that receives the attribute information. The type of attribute information that is stored into this buffer /// is determined by the value of fInfoLevelId. /// /// /// If the function succeeds, the return value is a nonzero value. If the function fails, the return value is zero(0). To get /// extended error information, call GetLastError. /// [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [PInvokeData("FileAPI.h", MSDNShortId = "aa364946")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetFileAttributesEx( string lpFileName, GET_FILEEX_INFO_LEVELS fInfoLevelId, out WIN32_FILE_ATTRIBUTE_DATA lpFileInformation); /// /// Retrieves file information for the specified file. /// For a more advanced version of this function, see GetFileInformationByHandleEx. /// To set file information using a file handle, see SetFileInformationByHandle. /// /// /// A handle to the file that contains the information to be retrieved. /// This handle should not be a pipe handle. /// /// /// A pointer to a BY_HANDLE_FILE_INFORMATION structure that receives the file information. /// /// /// /// If the function succeeds, the return value is nonzero and file information data is contained in the buffer pointed to by the /// lpFileInformation parameter. /// /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// // BOOL WINAPI GetFileInformationByHandle( _In_ HANDLE hFile, _Out_ LPBY_HANDLE_FILE_INFORMATION lpFileInformation); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("FileAPI.h", MSDNShortId = "aa364952")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetFileInformationByHandle([In] HFILE hFile, out BY_HANDLE_FILE_INFORMATION lpFileInformation); /// /// Retrieves the size of the specified file, in bytes. /// It is recommended that you use GetFileSizeEx. /// /// /// A handle to the file. /// /// /// /// A pointer to the variable where the high-order doubleword of the file size is returned. This parameter can be NULL if the /// application does not require the high-order doubleword. /// /// /// /// /// If the function succeeds, the return value is the low-order doubleword of the file size, and, if lpFileSizeHigh is non- /// NULL, the function puts the high-order doubleword of the file size into the variable pointed to by that parameter. /// /// /// If the function fails and lpFileSizeHigh is NULL, the return value is INVALID_FILE_SIZE. To get extended error /// information, call GetLastError. When lpFileSizeHigh is NULL, the results returned for large files are ambiguous, /// and you will not be able to determine the actual size of the file. It is recommended that you use GetFileSizeEx instead. /// /// /// If the function fails and lpFileSizeHigh is non- NULL, the return value is INVALID_FILE_SIZE and /// GetLastError will return a value other than NO_ERROR. /// /// // DWORD WINAPI GetFileSize( _In_ HANDLE hFile, _Out_opt_ LPDWORD lpFileSizeHigh); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("FileAPI.h", MSDNShortId = "aa364955")] public static extern uint GetFileSize([In] HFILE hFile, out uint lpFileSizeHigh); /// /// Retrieves the size of the specified file. /// /// /// /// A handle to the file. The handle must have been created with the FILE_READ_ATTRIBUTES access right or equivalent, or the /// caller must have sufficient permission on the directory that contains the file. For more information, see File Security and /// Access Rights. /// /// /// /// A pointer to a LARGE_INTEGER structure that receives the file size, in bytes. /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// // BOOL WINAPI GetFileSizeEx( _In_ HANDLE hFile, _Out_ PLARGE_INTEGER lpFileSize); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("FileAPI.h", MSDNShortId = "aa364957")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetFileSizeEx([In] HFILE hFile, out long lpFileSize); /// /// Retrieves the date and time that a file or directory was created, last accessed, and last modified. /// /// /// /// A handle to the file or directory for which dates and times are to be retrieved. The handle must have been created using the /// CreateFile function with the GENERIC_READ access right. For more information, see File Security and Access Rights. /// /// /// /// /// A pointer to a FILETIME structure to receive the date and time the file or directory was created. This parameter can be /// NULL if the application does not require this information. /// /// /// /// /// A pointer to a FILETIME structure to receive the date and time the file or directory was last accessed. The last access /// time includes the last time the file or directory was written to, read from, or, in the case of executable files, run. This /// parameter can be NULL if the application does not require this information. /// /// /// /// /// A pointer to a FILETIME structure to receive the date and time the file or directory was last written to, truncated, or /// overwritten (for example, with WriteFile or SetEndOfFile). This date and time is not updated when file attributes /// or security descriptors are changed. This parameter can be NULL if the application does not require this information. /// /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// // BOOL WINAPI GetFileTime( _In_ HANDLE hFile, _Out_opt_ LPFILETIME lpCreationTime, _Out_opt_ LPFILETIME lpLastAccessTime, _Out_opt_ // LPFILETIME lpLastWriteTime); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("FileAPI.h", MSDNShortId = "ms724320")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetFileTime([In] HFILE hFile, out FILETIME lpCreationTime, out FILETIME lpLastAccessTime, out FILETIME lpLastWriteTime); /// /// Retrieves the file type of the specified file. /// /// /// A handle to the file. /// /// /// The function returns one of the following values. /// /// /// /// Return code/value /// Description /// /// /// FILE_TYPE_CHAR = 0x0002 /// The specified file is a character file, typically an LPT device or a console. /// /// /// FILE_TYPE_DISK = 0x0001 /// The specified file is a disk file. /// /// /// FILE_TYPE_PIPE = 0x0003 /// The specified file is a socket, a named pipe, or an anonymous pipe. /// /// /// FILE_TYPE_REMOTE = 0x8000 /// Unused. /// /// /// FILE_TYPE_UNKNOWN = 0x0000 /// Either the type of the specified file is unknown, or the function failed. /// /// /// /// /// You can distinguish between a "valid" return of FILE_TYPE_UNKNOWN and its return due to a calling error (for example, /// passing an invalid handle to GetFileType) by calling GetLastError. /// /// If the function worked properly and FILE_TYPE_UNKNOWN was returned, a call to GetLastError will return NO_ERROR. /// /// If the function returned FILE_TYPE_UNKNOWN due to an error in calling GetFileType, GetLastError will return /// the error code. /// /// // DWORD WINAPI GetFileType( _In_ HANDLE hFile); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("FileAPI.h", MSDNShortId = "aa364960")] public static extern FileType GetFileType([In] HFILE hFile); /// /// Retrieves the final path for the specified file. /// For more information about file and path names, see Naming a File. /// /// /// A handle to a file or directory. /// /// /// A pointer to a buffer that receives the path of hFile. /// /// /// The size of lpszFilePath, in TCHAR s. This value does not include a NULL termination character. /// /// /// The type of result to return. This parameter can be one of the following values. /// /// /// /// Value /// Meaning /// /// /// FILE_NAME_NORMALIZED = 0x0 /// Return the normalized drive name. This is the default. /// /// /// FILE_NAME_OPENED = 0x8 /// Return the opened file name (not normalized). /// /// /// /// This parameter can also include one of the following values. /// /// /// /// Value /// Meaning /// /// /// VOLUME_NAME_DOS = 0x0 /// Return the path with the drive letter. This is the default. /// /// /// VOLUME_NAME_GUID = 0x1 /// Return the path with a volume GUID path instead of the drive name. /// /// /// VOLUME_NAME_NONE = 0x4 /// Return the path with no drive information. /// /// /// VOLUME_NAME_NT = 0x2 /// Return the path with the volume device path. /// /// /// /// /// /// /// If the function succeeds, the return value is the length of the string received by lpszFilePath, in TCHAR s. This value /// does not include the size of the terminating null character. /// /// /// Windows Server 2008 and Windows Vista: For the ANSI version of this function, GetFinalPathNameByHandleA, the return /// value includes the size of the terminating null character. /// /// /// If the function fails because lpszFilePath is too small to hold the string plus the terminating null character, the return value /// is the required buffer size, in TCHAR s. This value includes the size of the terminating null character. /// /// If the function fails for any other reason, the return value is zero. To get extended error information, call GetLastError. /// /// /// /// Return code /// Description /// /// /// ERROR_PATH_NOT_FOUND /// /// Can be returned if you are searching for a drive letter and one does not exist. For example, the handle was opened on a drive /// that is not currently mounted, or if you create a volume and do not assign it a drive letter. If a volume has no drive letter, /// you can use the volume GUID path to identify it.This return value can also be returned if you are searching for a volume GUID /// path on a network share. Volume GUID paths are not created for network shares. /// /// /// /// ERROR_NOT_ENOUGH_MEMORY /// Insufficient memory to complete the operation. /// /// /// ERROR_INVALID_PARAMETER /// Invalid flags were specified for dwFlags. /// /// /// /// // DWORD WINAPI GetFinalPathNameByHandle( _In_ HANDLE hFile, _Out_ LPTSTR lpszFilePath, _In_ DWORD cchFilePath, _In_ DWORD dwFlags); [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [PInvokeData("FileAPI.h", MSDNShortId = "aa364962")] public static extern uint GetFinalPathNameByHandle([In] HFILE hFile, StringBuilder lpszFilePath, uint cchFilePath, FinalPathNameOptions dwFlags); /// /// Retrieves the full path and file name of the specified file. /// To perform this operation as a transacted operation, use the GetFullPathNameTransacted function. /// For more information about file and path names, see File Names, Paths, and Namespaces. /// /// /// The name of the file. /// This parameter can be a short (the 8.3 form) or long file name. This string can also be a share or volume name. /// /// In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to 32,767 wide /// characters, call the Unicode version of the function ( GetFullPathNameW), and prepend "\\?\" to the path. For more /// information, see Naming a File. /// /// /// /// The size of the buffer to receive the null-terminated string for the drive and path, in TCHARs. /// /// /// A pointer to a buffer that receives the null-terminated string for the drive and path. /// /// /// A pointer to a buffer that receives the address (within lpBuffer) of the final file name component in the path. /// This parameter can be NULL. /// If lpBuffer refers to a directory and not a file, lpFilePart receives zero. /// /// /// /// If the function succeeds, the return value is the length, in TCHARs, of the string copied to lpBuffer, not including the /// terminating null character. /// /// /// If the lpBuffer buffer is too small to contain the path, the return value is the size, in TCHARs, of the buffer that is /// required to hold the path and the terminating null character. /// /// If the function fails for any other reason, the return value is zero. To get extended error information, call GetLastError. /// // DWORD WINAPI GetFullPathName( _In_ LPCTSTR lpFileName, _In_ DWORD nBufferLength, _Out_ LPTSTR lpBuffer, _Out_ LPTSTR *lpFilePart); [DllImport(Lib.Kernel32, SetLastError = true, EntryPoint = "GetFullPathNameW", CharSet = CharSet.Unicode)] [PInvokeData("FileAPI.h", MSDNShortId = "aa364963")] public static extern uint GetFullPathName(string lpFileName, uint nBufferLength, StringBuilder lpBuffer, out IntPtr lpFilePart); /// /// Retrieves a bitmask representing the currently available disk drives. /// /// /// /// If the function succeeds, the return value is a bitmask representing the currently available disk drives. Bit position 0 (the /// least-significant bit) is drive A, bit position 1 is drive B, bit position 2 is drive C, and so on. /// /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// // DWORD WINAPI GetLogicalDrives(void); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("FileAPI.h", MSDNShortId = "aa364972")] public static extern uint GetLogicalDrives(); /// /// Fills a buffer with strings that specify valid drives in the system. /// /// /// /// The maximum size of the buffer pointed to by lpBuffer, in TCHARs. This size does not include the terminating null /// character. If this parameter is zero, lpBuffer is not used. /// /// /// /// /// A pointer to a buffer that receives a series of null-terminated strings, one for each valid drive in the system, plus with an /// additional null character. Each string is a device name. /// /// /// /// /// If the function succeeds, the return value is the length, in characters, of the strings copied to the buffer, not including the /// terminating null character. Note that an ANSI-ASCII null character uses one byte, but a Unicode (UTF-16) null character uses two bytes. /// /// /// If the buffer is not large enough, the return value is greater than nBufferLength. It is the size of the buffer required to hold /// the drive strings. /// /// If the function fails, the return value is zero. To get extended error information, use the GetLastError function. /// // DWORD WINAPI GetLogicalDriveStrings( _In_ DWORD nBufferLength, _Out_ LPTSTR lpBuffer); [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [PInvokeData("FileAPI.h", MSDNShortId = "aa364975")] public static extern uint GetLogicalDriveStrings(uint nBufferLength, StringBuilder lpBuffer); /// /// Converts the specified path to its long form. /// To perform this operation as a transacted operation, use the GetLongPathNameTransacted function. /// For more information about file and path names, see Naming Files, Paths, and Namespaces. /// /// /// The path to be converted. /// /// In the ANSI version of this function, GetLongPathNameA, the name is limited to MAX_PATH (260) characters. To extend /// this limit to 32,767 wide characters, call the Unicode version of the function, GetLongPathNameW, and prepend "\\?\" to /// the path. For more information, see Naming Files, Paths, and Namespaces. /// /// /// /// A pointer to the buffer to receive the long path. /// You can use the same buffer you used for the lpszShortPath parameter. /// /// /// The size of the buffer lpszLongPath points to, in TCHARs. /// /// /// /// If the function succeeds, the return value is the length, in TCHARs, of the string copied to lpszLongPath, not including /// the terminating null character. /// /// /// If the lpBuffer buffer is too small to contain the path, the return value is the size, in TCHARs, of the buffer that is /// required to hold the path and the terminating null character. /// /// /// If the function fails for any other reason, such as if the file does not exist, the return value is zero. To get extended error /// information, call GetLastError. /// /// // DWORD WINAPI GetLongPathName( _In_ LPCTSTR lpszShortPath, _Out_ LPTSTR lpszLongPath, _In_ DWORD cchBuffer); [DllImport(Lib.Kernel32, SetLastError = true, EntryPoint = "GetLongPathNameW", CharSet = CharSet.Unicode)] [PInvokeData("FileAPI.h", MSDNShortId = "aa364980")] public static extern uint GetLongPathName(string lpszShortPath, StringBuilder lpszLongPath, uint cchBuffer); /// /// Retrieves the short path form of the specified path. /// For more information about file and path names, see Naming Files, Paths, and Namespaces. /// /// /// The path string. /// /// In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to 32,767 wide /// characters, call the Unicode version of the function and prepend "\\?\" to the path. For more information, see Naming Files, /// Paths, and Namespaces. /// /// /// /// A pointer to a buffer to receive the null-terminated short form of the path that lpszLongPath specifies. /// /// Passing NULL for this parameter and zero for cchBuffer will always return the required buffer size for a specified lpszLongPath. /// /// /// /// The size of the buffer that lpszShortPath points to, in TCHARs. /// Set this parameter to zero if lpszShortPath is set to NULL. /// /// /// /// If the function succeeds, the return value is the length, in TCHARs, of the string that is copied to lpszShortPath, not /// including the terminating null character. /// /// /// If the lpszShortPath buffer is too small to contain the path, the return value is the size of the buffer, in TCHARs, that /// is required to hold the path and the terminating null character. /// /// If the function fails for any other reason, the return value is zero. To get extended error information, call GetLastError. /// // DWORD WINAPI GetShortPathName( _In_ LPCTSTR lpszLongPath, _Out_ LPTSTR lpszShortPath, _In_ DWORD cchBuffer); [DllImport(Lib.Kernel32, SetLastError = true, EntryPoint = "GetShortPathNameW", CharSet = CharSet.Unicode)] [PInvokeData("FileAPI.h", MSDNShortId = "aa364989")] public static extern uint GetShortPathName(string lpszLongPath, StringBuilder lpszShortPath, uint cchBuffer); /// /// Creates a name for a temporary file. If a unique file name is generated, an empty file is created and the handle to it is /// released; otherwise, only a file name is generated. /// /// /// The directory path for the file name. Applications typically specify a period (.) for the current directory or the result of the /// GetTempPath function. The string cannot be longer than MAX_PATH–14 characters or GetTempFileName will fail. If this /// parameter is NULL, the function fails. /// /// /// The null-terminated prefix string. The function uses up to the first three characters of this string as the prefix of the file /// name. This string must consist of characters in the OEM-defined character set. /// /// /// An unsigned integer to be used in creating the temporary file name. For more information, see Remarks. /// /// If uUnique is zero, the function attempts to form a unique file name using the current system time. If the file already exists, /// the number is increased by one and the functions tests if this file already exists. This continues until a unique filename is /// found; the function creates a file by that name and closes it. Note that the function does not attempt to verify the uniqueness /// of the file name when uUnique is nonzero. /// /// /// /// A pointer to the buffer that receives the temporary file name. This buffer should be MAX_PATH characters to accommodate /// the path plus the terminating null character. /// /// /// /// If the function succeeds, the return value specifies the unique numeric value used in the temporary file name. If the uUnique /// parameter is nonzero, the return value specifies that same number. /// /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// The following is a possible return value. /// /// /// Return value /// Description /// /// /// ERROR_BUFFER_OVERFLOW /// The length of the string pointed to by the lpPathName parameter is more than MAX_PATH–14 characters. /// /// /// /// /// The GetTempFileName function creates a temporary file name of the following form: /// <path><i><pre><uuuu>.TMP /// The following table describes the file name syntax. /// /// /// Component /// Meaning /// /// /// <path> /// Path specified by the lpPathName parameter /// /// /// <pre> /// First three letters of the lpPrefixString string /// /// /// <uuuu> /// Hexadecimal value of uUnique /// /// /// /// If uUnique is zero, GetTempFileName creates an empty file and closes it. If uUnique is not zero, you must create the file /// yourself. Only a file name is created, because GetTempFileName is not able to guarantee that the file name is unique. /// /// /// Only the lower 16 bits of the uUnique parameter are used. This limits GetTempFileName to a maximum of 65,535 unique file /// names if the lpPathName and lpPrefixString parameters remain the same. /// /// /// Due to the algorithm used to generate file names, GetTempFileName can perform poorly when creating a large number of files /// with the same prefix. In such cases, it is recommended that you construct unique file names based on GUID s. /// /// /// Temporary files whose names have been created by this function are not automatically deleted. To delete these files call DeleteFile. /// /// /// To avoid problems resulting when converting an ANSI string, an application should call the CreateFile function to create a /// temporary file. /// /// In Windows 8 and Windows Server 2012, this function is supported by the following technologies. /// /// /// Technology /// Supported /// /// /// Server Message Block (SMB) 3.0 protocol /// Yes /// /// /// SMB 3.0 Transparent Failover (TFO) /// Yes /// /// /// SMB 3.0 with Scale-out File Shares (SO) /// Yes /// /// /// Cluster Shared Volume File System (CsvFS) /// Yes /// /// /// Resilient File System (ReFS) /// Yes /// /// /// Examples /// For an example, see Creating and Using a Temporary File. /// // https://docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-gettempfilenamea UINT GetTempFileNameA( LPCSTR lpPathName, // LPCSTR lpPrefixString, UINT uUnique, LPSTR lpTempFileName ); [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [PInvokeData("fileapi.h", MSDNShortId = "0a30055f-a3b9-439f-9304-40ee8a07b967")] public static extern uint GetTempFileName(string lpPathName, string lpPrefixString, uint uUnique, [Out] StringBuilder lpTempFileName); /// /// Retrieves the path of the directory designated for temporary files. /// /// /// The size of the string buffer identified by lpBuffer, in TCHARs. /// /// /// /// A pointer to a string buffer that receives the null-terminated string specifying the temporary file path. The returned string /// ends with a backslash, for example, "C:\TEMP\". /// /// /// /// /// If the function succeeds, the return value is the length, in TCHARs, of the string copied to lpBuffer, not including the /// terminating null character. If the return value is greater than nBufferLength, the return value is the length, in TCHARs, /// of the buffer required to hold the path. /// /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// The maximum possible return value is MAX_PATH+1 (261). /// // DWORD WINAPI GetTempPath( _In_ DWORD nBufferLength, _Out_ LPTSTR lpBuffer); [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [PInvokeData("FileAPI.h", MSDNShortId = "aa364992")] public static extern uint GetTempPath(uint nBufferLength, StringBuilder lpBuffer); /// Retrieves information about the file system and volume associated with the specified root directory. /// /// A pointer to a string that contains the root directory of the volume to be described. /// /// If this parameter is NULL, the root of the current directory is used. A trailing backslash is required. For example, you specify /// \\MyServer\MyShare as "\\MyServer\MyShare\", or the C drive as "C:\". /// /// /// /// A pointer to a buffer that receives the name of a specified volume. The buffer size is specified by the /// parameter. /// /// /// The length of a volume name buffer, in TCHARs. The maximum buffer size is MAX_PATH+1. /// This parameter is ignored if the volume name buffer is not supplied. /// /// /// A pointer to a variable that receives the volume serial number. /// This parameter can be NULL if the serial number is not required. /// /// This function returns the volume serial number that the operating system assigns when a hard disk is formatted. To /// programmatically obtain the hard disk's serial number that the manufacturer assigns, use the Windows Management Instrumentation /// (WMI) Win32_PhysicalMedia property SerialNumber. /// /// /// /// A pointer to a variable that receives the maximum length, in TCHARs, of a file name component that a specified file system supports. /// A file name component is the portion of a file name between backslashes. /// /// The value that is stored in the variable that points to is used to indicate that a /// specified file system supports long names. For example, for a FAT file system that supports long names, the function stores the /// value 255, rather than the previous 8.3 indicator. Long names can also be supported on systems that use the NTFS file system. /// /// /// /// A pointer to a variable that receives flags associated with the specified file system. /// /// This parameter can be one or more of the FileSystemFlags values. However, FILE_FILE_COMPRESSION and FILE_VOL_IS_COMPRESSED /// are mutually exclusive. /// /// /// /// A pointer to a buffer that receives the name of the file system, for example, the FAT file system or the NTFS file system. The /// buffer size is specified by the parameter. /// /// /// The length of the file system name buffer, in TCHARs. The maximum buffer size is MAX_PATH+1. /// This parameter is ignored if the file system name buffer is not supplied. /// /// /// If all the requested information is retrieved, the return value is nonzero. /// If not all the requested information is retrieved, the return value is zero. To get extended error information, call GetLastError. /// /// /// When a user attempts to get information about a floppy drive that does not have a floppy disk, or a CD-ROM drive that does not /// have a compact disc, the system displays a message box for the user to insert a floppy disk or a compact disc, respectively. To /// prevent the system from displaying this message box, call the SetErrorMode function with SEM_FAILCRITICALERRORS. /// /// The FILE_VOL_IS_COMPRESSED flag is the only indicator of volume-based compression. The file system name is not altered to /// indicate compression, for example, this flag is returned set on a DoubleSpace volume. When compression is volume-based, an entire /// volume is compressed or not compressed. /// /// /// The FILE_FILE_COMPRESSION flag indicates whether a file system supports file-based compression. When compression is file-based, /// individual files can be compressed or not compressed. /// /// The FILE_FILE_COMPRESSION and FILE_VOL_IS_COMPRESSED flags are mutually exclusive. Both bits cannot be returned set. /// /// The maximum component length value that is stored in lpMaximumComponentLength is the only indicator that a volume supports /// longer-than-normal FAT file system (or other file system) file names. The file system name is not altered to indicate support for /// long file names. /// /// /// The GetCompressedFileSize function obtains the compressed size of a file. The GetFileAttributes function can determine whether an /// individual file is compressed. /// /// Symbolic link behavior— /// If the path points to a symbolic link, the function returns volume information for the target. /// [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] [PInvokeData("FileAPI.h", MSDNShortId = "aa364993")] public static extern bool GetVolumeInformation(string lpRootPathName, StringBuilder lpVolumeNameBuffer, int nVolumeNameSize, out uint lpVolumeSerialNumber, out uint lpMaximumComponentLength, out FileSystemFlags lpFileSystemFlags, StringBuilder lpFileSystemNameBuffer, int nFileSystemNameSize); /// Retrieves information about the file system and volume associated with the specified root directory. /// /// A string that contains the root directory of the volume to be described. /// /// If this parameter is NULL, the root of the current directory is used. A trailing backslash is required. For example, you specify /// \\MyServer\MyShare as "\\MyServer\MyShare\", or the C drive as "C:\". /// /// /// Receives the name of a specified volume. /// /// Receives the volume serial number. /// /// This function returns the volume serial number that the operating system assigns when a hard disk is formatted. To /// programmatically obtain the hard disk's serial number that the manufacturer assigns, use the Windows Management Instrumentation /// (WMI) Win32_PhysicalMedia property SerialNumber. /// /// /// /// Receives the maximum length, in characters, of a file name component that a specified file system supports. /// A file name component is the portion of a file name between backslashes. /// /// The value that is stored in the variable that returns is used to indicate that a /// specified file system supports long names. For example, for a FAT file system that supports long names, the function stores the /// value 255, rather than the previous 8.3 indicator. Long names can also be supported on systems that use the NTFS file system. /// /// /// /// Receives the flags associated with the specified file system. /// /// This parameter can be one or more of the FileSystemFlags values. However, FILE_FILE_COMPRESSION and FILE_VOL_IS_COMPRESSED /// are mutually exclusive. /// /// /// Receives the name of the file system, for example, the FAT file system or the NTFS file system. /// /// If all the requested information is retrieved, the return value is nonzero. /// If not all the requested information is retrieved, the return value is zero. To get extended error information, call GetLastError. /// /// /// When a user attempts to get information about a floppy drive that does not have a floppy disk, or a CD-ROM drive that does not /// have a compact disc, the system displays a message box for the user to insert a floppy disk or a compact disc, respectively. To /// prevent the system from displaying this message box, call the SetErrorMode function with SEM_FAILCRITICALERRORS. /// /// The FILE_VOL_IS_COMPRESSED flag is the only indicator of volume-based compression. The file system name is not altered to /// indicate compression, for example, this flag is returned set on a DoubleSpace volume. When compression is volume-based, an entire /// volume is compressed or not compressed. /// /// /// The FILE_FILE_COMPRESSION flag indicates whether a file system supports file-based compression. When compression is file-based, /// individual files can be compressed or not compressed. /// /// The FILE_FILE_COMPRESSION and FILE_VOL_IS_COMPRESSED flags are mutually exclusive. Both bits cannot be returned set. /// /// The maximum component length value that is stored in lpMaximumComponentLength is the only indicator that a volume supports /// longer-than-normal FAT file system (or other file system) file names. The file system name is not altered to indicate support for /// long file names. /// /// /// The GetCompressedFileSize function obtains the compressed size of a file. The GetFileAttributes function can determine whether an /// individual file is compressed. /// /// Symbolic link behavior— /// If the path points to a symbolic link, the function returns volume information for the target. /// [PInvokeData("FileAPI.h", MSDNShortId = "aa364993")] public static bool GetVolumeInformation(string rootPathName, out string volumeName, out uint volumeSerialNumber, out uint maximumComponentLength, out FileSystemFlags fileSystemFlags, out string fileSystemName) { var sb1 = new StringBuilder(MAX_PATH + 1); var sb2 = new StringBuilder(MAX_PATH + 1); var ret = GetVolumeInformation(rootPathName, sb1, sb1.Capacity, out var sn, out var cl, out var flags, sb2, sb2.Capacity); volumeName = sb1.ToString(); volumeSerialNumber = sn; maximumComponentLength = cl; fileSystemFlags = flags; fileSystemName = sb2.ToString(); return ret; } /// /// Retrieves information about the file system and volume associated with the specified file. /// To retrieve the current compression state of a file or directory, use FSCTL_GET_COMPRESSION. /// /// /// A handle to the file. /// /// /// A pointer to a buffer that receives the name of a specified volume. The maximum buffer size is . /// /// /// The length of a volume name buffer, in WCHAR s. The maximum buffer size is . /// This parameter is ignored if the volume name buffer is not supplied. /// /// /// A pointer to a variable that receives the volume serial number. /// This parameter can be NULL if the serial number is not required. /// /// This function returns the volume serial number that the operating system assigns when a hard disk is formatted. To /// programmatically obtain the hard disk's serial number that the manufacturer assigns, use the Windows Management Instrumentation /// (WMI) Win32_PhysicalMedia property SerialNumber. /// /// /// /// /// A pointer to a variable that receives the maximum length, in WCHAR s, of a file name component that a specified file /// system supports. /// /// A file name component is the portion of a file name between backslashes. /// /// The value that is stored in the variable that *lpMaximumComponentLength points to is used to indicate that a specified file /// system supports long names. For example, for a FAT file system that supports long names, the function stores the value 255, /// rather than the previous 8.3 indicator. Long names can also be supported on systems that use the NTFS file system. /// /// /// /// A pointer to a variable that receives flags associated with the specified file system. /// /// This parameter can be one or more of the following flags. However, FILE_FILE_COMPRESSION and FILE_VOL_IS_COMPRESSED /// are mutually exclusive. /// /// /// /// /// Value /// Meaning /// /// /// FILE_CASE_PRESERVED_NAMES0x00000002 /// The specified volume supports preserved case of file names when it places a name on disk. /// /// /// FILE_CASE_SENSITIVE_SEARCH0x00000001 /// The specified volume supports case-sensitive file names. /// /// /// FILE_FILE_COMPRESSION0x00000010 /// The specified volume supports file-based compression. /// /// /// FILE_NAMED_STREAMS0x00040000 /// The specified volume supports named streams. /// /// /// FILE_PERSISTENT_ACLS0x00000008 /// /// The specified volume preserves and enforces access control lists (ACL). For example, the NTFS file system preserves and enforces /// ACLs, and the FAT file system does not. /// /// /// /// FILE_READ_ONLY_VOLUME0x00080000 /// The specified volume is read-only. /// /// /// FILE_SEQUENTIAL_WRITE_ONCE0x00100000 /// The specified volume supports a single sequential write. /// /// /// FILE_SUPPORTS_ENCRYPTION0x00020000 /// The specified volume supports the Encrypted File System (EFS). For more information, see File Encryption. /// /// /// FILE_SUPPORTS_EXTENDED_ATTRIBUTES0x00800000 /// /// The specified volume supports extended attributes. An extended attribute is a piece of application-specific metadata that an /// application can associate with a file and is not part of the file's data.Windows Vista and Windows Server 2008: This value is not supported. /// /// /// /// FILE_SUPPORTS_HARD_LINKS0x00400000 /// /// The specified volume supports hard links. For more information, see Hard Links and Junctions.Windows Vista and Windows Server /// 2008: This value is not supported. /// /// /// /// FILE_SUPPORTS_OBJECT_IDS0x00010000 /// The specified volume supports object identifiers. /// /// /// FILE_SUPPORTS_OPEN_BY_FILE_ID0x01000000 /// /// The file system supports open by FileID. For more information, see FILE_ID_BOTH_DIR_INFO.Windows Vista and Windows Server 2008: /// This value is not supported. /// /// /// /// FILE_SUPPORTS_REPARSE_POINTS0x00000080 /// The specified volume supports re-parse points. /// /// /// FILE_SUPPORTS_SPARSE_FILES0x00000040 /// The specified volume supports sparse files. /// /// /// FILE_SUPPORTS_TRANSACTIONS0x00200000 /// The specified volume supports transactions. For more information, see About KTM. /// /// /// FILE_SUPPORTS_USN_JOURNAL0x02000000 /// /// The specified volume supports update sequence number (USN) journals. For more information, see Change Journal Records.Windows /// Vista and Windows Server 2008: This value is not supported. /// /// /// /// FILE_UNICODE_ON_DISK0x00000004 /// The specified volume supports Unicode in file names as they appear on disk. /// /// /// FILE_VOLUME_IS_COMPRESSED0x00008000 /// The specified volume is a compressed volume. /// /// /// FILE_VOLUME_QUOTAS0x00000020 /// The specified volume supports disk quotas. /// /// /// /// /// /// /// A pointer to a buffer that receives the name of the file system, for example, the FAT file system or the NTFS file system. The /// buffer size is specified by the nFileSystemNameSize parameter. /// /// /// /// The length of the file system name buffer, in WCHAR s. The maximum buffer size is . /// This parameter is ignored if the file system name buffer is not supplied. /// /// /// If all the requested information is retrieved, the return value is nonzero. /// If not all the requested information is retrieved, the return value is zero. To get extended error information, call GetLastError. /// // BOOL WINAPI GetVolumeInformationByHandleW( _In_ HANDLE hFile, _Out_opt_ LPWSTR lpVolumeNameBuffer, _In_ DWORD nVolumeNameSize, // _Out_opt_ LPDWORD lpVolumeSerialNumber, _Out_opt_ LPDWORD lpMaximumComponentLength, _Out_opt_ LPDWORD lpFileSystemFlags, _Out_opt_ // LPWSTR lpFileSystemNameBuffer, _In_ DWORD nFileSystemNameSize); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("FileAPI.h", MSDNShortId = "aa964920")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetVolumeInformationByHandleW([In] HFILE hFile, StringBuilder lpVolumeNameBuffer, uint nVolumeNameSize, out uint lpVolumeSerialNumber, out uint lpMaximumComponentLength, out FileSystemFlags lpFileSystemFlags, StringBuilder lpFileSystemNameBuffer, uint nFileSystemNameSize); /// /// /// Retrieves a volume GUID path for the volume that is associated with the specified volume mount point ( drive letter, /// volume GUID path, or mounted folder). /// /// /// /// /// A pointer to a string that contains the path of a mounted folder (for example, "Y:\MountX\") or a drive letter (for example, /// "X:\"). The string must end with a trailing backslash ('\'). /// /// /// /// /// A pointer to a string that receives the volume GUID path. This path is of the form "\\?\Volume{GUID}\" where GUID is a /// GUID that identifies the volume. If there is more than one volume GUID path for the volume, only the first one in /// the mount manager's cache is returned. /// /// /// /// /// The length of the output buffer, in TCHARs. A reasonable size for the buffer to accommodate the largest possible volume /// GUID path is 50 characters. /// /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// // BOOL WINAPI GetVolumeNameForVolumeMountPoint( _In_ LPCTSTR lpszVolumeMountPoint, _Out_ LPTSTR lpszVolumeName, _In_ DWORD cchBufferLength); [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [PInvokeData("FileAPI.h", MSDNShortId = "aa364994")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetVolumeNameForVolumeMountPoint(string lpszVolumeMountPoint, StringBuilder lpszVolumeName, uint cchBufferLength); /// /// Retrieves the volume mount point where the specified path is mounted. /// /// /// /// A pointer to the input path string. Both absolute and relative file and directory names, for example "..", are acceptable in this path. /// /// /// If you specify a relative directory or file name without a volume qualifier, GetVolumePathName returns the drive letter of /// the boot volume. /// /// If this parameter is an empty string, "", the function fails but the last error is set to ERROR_SUCCESS. /// /// /// A pointer to a string that receives the volume mount point for the input path. /// /// /// The length of the output buffer, in TCHARs. /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// // BOOL WINAPI GetVolumePathName( _In_ LPCTSTR lpszFileName, _Out_ LPTSTR lpszVolumePathName, _In_ DWORD cchBufferLength); [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [PInvokeData("FileAPI.h", MSDNShortId = "aa364996")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetVolumePathName(string lpszFileName, StringBuilder lpszVolumePathName, uint cchBufferLength); /// /// Retrieves a list of drive letters and mounted folder paths for the specified volume. /// /// /// A volume GUID path for the volume. A volume GUID path is of the form "\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\". /// /// /// /// A pointer to a buffer that receives the list of drive letters and mounted folder paths. The list is an array of null-terminated /// strings terminated by an additional NULL character. If the buffer is not large enough to hold the complete list, the /// buffer holds as much of the list as possible. /// /// /// /// The length of the lpszVolumePathNames buffer, in TCHARs, including all NULL characters. /// /// /// /// If the call is successful, this parameter is the number of TCHARs copied to the lpszVolumePathNames buffer. Otherwise, /// this parameter is the size of the buffer required to hold the complete list, in TCHARs. /// /// /// /// If the function succeeds, the return value is nonzero. /// /// If the function fails, the return value is zero. To get extended error information, call GetLastError. If the buffer is /// not large enough to hold the complete list, the error code is ERROR_MORE_DATA and the lpcchReturnLength parameter receives /// the required buffer size. /// /// // BOOL WINAPI GetVolumePathNamesForVolumeName( _In_ LPCTSTR lpszVolumeName, _Out_ LPTSTR lpszVolumePathNames, _In_ DWORD // cchBufferLength, _Out_ PDWORD lpcchReturnLength); [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [PInvokeData("FileAPI.h", MSDNShortId = "aa364998")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetVolumePathNamesForVolumeName(string lpszVolumeName, StringBuilder lpszVolumePathNames, uint cchBufferLength, out uint lpcchReturnLength); /// /// Converts a local file time to a file time based on the Coordinated Universal Time (UTC). /// /// /// A pointer to a FILETIME structure that specifies the local file time to be converted into a UTC-based file time. /// /// /// /// A pointer to a FILETIME structure to receive the converted UTC-based file time. This parameter cannot be the same as the /// lpLocalFileTime parameter. /// /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, use the GetLastError function. /// // BOOL WINAPI LocalFileTimeToFileTime( _In_ const FILETIME *lpLocalFileTime, _Out_ LPFILETIME lpFileTime); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("FileAPI.h", MSDNShortId = "ms724490")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool LocalFileTimeToFileTime(in FILETIME lpLocalFileTime, out FILETIME lpFileTime); /// /// Locks the specified file for exclusive access by the calling process. /// To specify additional options, for example creating a shared lock or for block-on-fail operation, use the LockFileEx function. /// /// /// A handle to the file. The file handle must have been created with the GENERIC_READ or GENERIC_WRITE access right. /// For more information, see File Security and Access Rights. /// /// The low-order 32 bits of the starting byte offset in the file where the lock should begin. /// The high-order 32 bits of the starting byte offset in the file where the lock should begin. /// The low-order 32 bits of the length of the byte range to be locked. /// The high-order 32 bits of the length of the byte range to be locked. /// /// If the function succeeds, the return value is nonzero ( TRUE). /// If the function fails, the return value is zero ( FALSE). To get extended error information, call GetLastError. /// /// /// /// If the call to LockFile completes synchronously, a completion entry may not be queued when a completion port is associated /// with the file handle. /// /// The UnlockFile function unlocks a file region locked by LockFile. /// /// Locking a region of a file gives the threads of the locking process exclusive access to the specified region using this file /// handle. If the file handle is inherited by a process created by the locking process, the child process is not granted access to /// the locked region. If the locking process opens the file a second time, it cannot access the specified region through this second /// handle until it unlocks the region. /// /// Locking a region of a file does not prevent reading from a mapped file view. /// /// You can lock bytes that are beyond the end of the current file. This is useful to coordinate adding records to the end of a file. /// /// Exclusive locks cannot overlap an existing locked region of a file. For more information, see LockFileEx. /// /// If LockFile cannot lock a region of a file, it returns zero immediately. It does not block. To issue a file lock request /// that will block until the lock is acquired, use LockFileEx without the LOCKFILE_FAIL_IMMEDIATELY flag. /// /// /// If a process terminates with a portion of a file locked or closes a file that has outstanding locks, the locks are unlocked by /// the operating system. However, the time it takes for the operating system to unlock these locks depends upon available system /// resources. Therefore, it is recommended that your process explicitly unlock all files it has locked when it terminates. If this /// is not done, access to these files may be denied if the operating system has not yet unlocked them. /// /// In Windows 8 and Windows Server 2012, this function is supported by the following technologies. /// /// /// Technology /// Supported /// /// /// Server Message Block (SMB) 3.0 protocol /// Yes /// /// /// SMB 3.0 Transparent Failover (TFO) /// Yes /// /// /// SMB 3.0 with Scale-out File Shares (SO) /// Yes /// /// /// Cluster Shared Volume File System (CsvFS) /// Yes /// /// /// Resilient File System (ReFS) /// Yes /// /// /// Examples /// For an example, see Appending One File to Another File. /// // https://docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-lockfile BOOL LockFile( HANDLE hFile, DWORD // dwFileOffsetLow, DWORD dwFileOffsetHigh, DWORD nNumberOfBytesToLockLow, DWORD nNumberOfBytesToLockHigh ); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("fileapi.h", MSDNShortId = "c88e7b6c-c339-443b-adf9-0325807203dc")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool LockFile([In] HFILE hFile, uint dwFileOffsetLow, uint dwFileOffsetHigh, uint nNumberOfBytesToLockLow, uint nNumberOfBytesToLockHigh); /// /// /// Locks the specified file for exclusive access by the calling process. This function can operate either synchronously or /// asynchronously and can request either an exclusive or a shared lock. /// /// /// /// /// A handle to the file. The handle must have been created with either the GENERIC_READ or GENERIC_WRITE access right. /// For more information, see File Security and Access Rights. /// /// /// /// This parameter may be one or more of the following values. /// /// /// /// Value /// Meaning /// /// /// LOCKFILE_EXCLUSIVE_LOCK = 0x00000002 /// The function requests an exclusive lock. Otherwise, it requests a shared lock. /// /// /// LOCKFILE_FAIL_IMMEDIATELY = 0x00000001 /// The function returns immediately if it is unable to acquire the requested lock. Otherwise, it waits. /// /// /// /// /// /// Reserved parameter; must be set to zero. /// /// /// The low-order 32 bits of the length of the byte range to lock. /// /// /// The high-order 32 bits of the length of the byte range to lock. /// /// /// /// A pointer to an OVERLAPPED structure that the function uses with the locking request. This structure, which is required, /// contains the file offset of the beginning of the lock range. You must initialize the hEvent member to a valid handle or zero. /// /// /// /// If the function succeeds, the return value is nonzero ( TRUE). /// If the function fails, the return value is zero ( FALSE). To get extended error information, call GetLastError. /// // BOOL WINAPI LockFileEx( _In_ HANDLE hFile, _In_ DWORD dwFlags, _Reserved_ DWORD dwReserved, _In_ DWORD nNumberOfBytesToLockLow, // _In_ DWORD nNumberOfBytesToLockHigh, _Inout_ LPOVERLAPPED lpOverlapped); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("FileAPI.h", MSDNShortId = "aa365203")] [return: MarshalAs(UnmanagedType.Bool)] public static extern unsafe bool LockFileEx([In] HFILE hFile, LOCKFILE dwFlags, [Optional] uint dwReserved, uint nNumberOfBytesToLockLow, uint nNumberOfBytesToLockHigh, NativeOverlapped* lpOverlapped); /// /// Retrieves information about MS-DOS device names. The function can obtain the current mapping for a particular MS-DOS device name. /// The function can also obtain a list of all existing MS-DOS device names. /// /// MS-DOS device names are stored as junctions in the object namespace. The code that converts an MS-DOS path into a corresponding /// path uses these junctions to map MS-DOS devices and drive letters. The QueryDosDevice function enables an application to query /// the names of the junctions used to implement the MS-DOS device namespace as well as the value of each specific junction. /// /// /// /// An MS-DOS device name string specifying the target of the query. The device name cannot have a trailing backslash; for example, /// use "C:", not "C:\". /// /// This parameter can be NULL. In that case, the QueryDosDevice function will store a list of all existing MS-DOS device names into /// the buffer pointed to by . /// /// /// /// A pointer to a buffer that will receive the result of the query. The function fills this buffer with one or more null-terminated /// strings. The final null-terminated string is followed by an additional NULL. /// /// If is non-NULL, the function retrieves information about the particular MS-DOS device specified /// by . The first null-terminated string stored into the buffer is the current mapping for the /// device. The other null-terminated strings represent undeleted prior mappings for the device. /// /// /// If is NULL, the function retrieves a list of all existing MS-DOS device names. Each /// null-terminated string stored into the buffer is the name of an existing MS-DOS device, for example, \Device\HarddiskVolume1 or \Device\Floppy0. /// /// /// The maximum number of TCHARs that can be stored into the buffer pointed to by . /// /// If the function succeeds, the return value is the number of TCHARs stored into the buffer pointed to by . /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// If the buffer is too small, the function fails and the last error code is ERROR_INSUFFICIENT_BUFFER. /// /// /// The DefineDosDevice function enables an application to create and modify the junctions used to implement the MS-DOS device namespace. /// /// Windows Server 2003 and Windows XP:QueryDosDevice first searches the Local MS-DOS Device namespace for the /// specified device name. If the device name is not found, the function will then search the Global MS-DOS Device namespace. /// /// /// When all existing MS-DOS device names are queried, the list of device names that are returned is dependent on whether it is /// running in the "LocalSystem" context. If so, only the device names included in the Global MS-DOS Device namespace will be /// returned. If not, a concatenation of the device names in the Global and Local MS-DOS Device namespaces will be returned. If a /// device name exists in both namespaces, QueryDosDevice will return the entry in the Local MS-DOS Device namespace. /// /// [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [PInvokeData("FileAPI.h", MSDNShortId = "aa365461")] public static extern int QueryDosDevice(string lpDeviceName, StringBuilder lpTargetPath, int ucchMax); /// /// Retrieves information about MS-DOS device names. The function can obtain the current mapping for a particular MS-DOS device name. /// The function can also obtain a list of all existing MS-DOS device names. /// /// MS-DOS device names are stored as junctions in the object namespace. The code that converts an MS-DOS path into a corresponding /// path uses these junctions to map MS-DOS devices and drive letters. The QueryDosDevice function enables an application to query /// the names of the junctions used to implement the MS-DOS device namespace as well as the value of each specific junction. /// /// /// /// An MS-DOS device name string specifying the target of the query. The device name cannot have a trailing backslash; for example, /// use "C:", not "C:\". /// /// This parameter can be NULL. In that case, the QueryDosDevice function will return a list of all existing MS-DOS device names. /// /// /// /// /// If is non-NULL, the function returns information about the particular MS-DOS device specified by /// . The first string returned is the current mapping for the device. The other strings represent /// undeleted prior mappings for the device. /// /// /// If is NULL, the function returns a list of all existing MS-DOS device names. Each string returned /// is the name of an existing MS-DOS device, for example, \Device\HarddiskVolume1 or \Device\Floppy0. /// /// [PInvokeData("FileAPI.h", MSDNShortId = "aa365461")] public static IEnumerable QueryDosDevice(string deviceName) { deviceName = deviceName?.TrimEnd('\\'); var bytes = 16; var retLen = 0U; using (var mem = new SafeHGlobalHandle(0)) { do { mem.Size = (bytes *= 4); retLen = QueryDosDevice(deviceName, (IntPtr)mem, mem.Size / Marshal.SystemDefaultCharSize); } while (retLen == 0 && Win32Error.GetLastError() == Win32Error.ERROR_INSUFFICIENT_BUFFER); if (retLen == 0) throw new Win32Exception(); return mem.ToStringEnum().ToArray(); } } /// /// Reads data from the specified file or input/output (I/O) device. Reads occur at the position specified by the file pointer if /// supported by the device. /// /// /// A handle to the device (for example, a file, file stream, physical disk, volume, console buffer, tape drive, socket, /// communications resource, mailslot, or pipe). The hFile parameter must have been created with read access. /// /// A pointer to the buffer that receives the data read from a file or device. /// The maximum number of bytes to be read. /// /// A pointer to the variable that receives the number of bytes read when using a synchronous hFile parameter. ReadFile sets this /// value to zero before doing any work or error checking. Use NULL for this parameter if this is an asynchronous operation to avoid /// potentially erroneous results. /// This parameter can be NULL only when the lpOverlapped parameter is not NULL. /// /// /// A pointer to an OVERLAPPED structure is required if the hFile parameter was opened with FILE_FLAG_OVERLAPPED, otherwise it can be NULL. /// /// If hFile is opened with FILE_FLAG_OVERLAPPED, the lpOverlapped parameter must point to a valid and unique OVERLAPPED structure, /// otherwise the function can incorrectly report that the read operation is complete. /// /// /// For an hFile that supports byte offsets, if you use this parameter you must specify a byte offset at which to start reading from /// the file or device. This offset is specified by setting the Offset and OffsetHigh members of the OVERLAPPED structure. For an /// hFile that does not support byte offsets, Offset and OffsetHigh are ignored. /// /// /// For more information about different combinations of lpOverlapped and FILE_FLAG_OVERLAPPED, see the Remarks section and the /// Synchronization and File Position section. /// /// /// /// If the function succeeds, the return value is nonzero (TRUE). If the function fails, or is completing asynchronously, the return /// value is zero(FALSE). To get extended error information, call the GetLastError function. /// [DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] [PInvokeData("FileAPI.h", MSDNShortId = "aa365467")] public static extern bool ReadFile(HFILE hFile, IntPtr lpBuffer, uint nNumberOfBytesToRead, out uint lpNumberOfBytesRead, [Optional] IntPtr lpOverlapped); /// /// Reads data from the specified file or input/output (I/O) device. Reads occur at the position specified by the file pointer if /// supported by the device. /// /// /// A handle to the device (for example, a file, file stream, physical disk, volume, console buffer, tape drive, socket, /// communications resource, mailslot, or pipe). The hFile parameter must have been created with read access. /// /// A pointer to the buffer that receives the data read from a file or device. /// The maximum number of bytes to be read. /// /// A pointer to the variable that receives the number of bytes read when using a synchronous hFile parameter. ReadFile sets this /// value to zero before doing any work or error checking. Use NULL for this parameter if this is an asynchronous operation to avoid /// potentially erroneous results. /// This parameter can be NULL only when the lpOverlapped parameter is not NULL. /// /// /// A pointer to an OVERLAPPED structure is required if the hFile parameter was opened with FILE_FLAG_OVERLAPPED, otherwise it can be NULL. /// /// If hFile is opened with FILE_FLAG_OVERLAPPED, the lpOverlapped parameter must point to a valid and unique OVERLAPPED structure, /// otherwise the function can incorrectly report that the read operation is complete. /// /// /// For an hFile that supports byte offsets, if you use this parameter you must specify a byte offset at which to start reading from /// the file or device. This offset is specified by setting the Offset and OffsetHigh members of the OVERLAPPED structure. For an /// hFile that does not support byte offsets, Offset and OffsetHigh are ignored. /// /// /// For more information about different combinations of lpOverlapped and FILE_FLAG_OVERLAPPED, see the Remarks section and the /// Synchronization and File Position section. /// /// /// /// If the function succeeds, the return value is nonzero (TRUE). If the function fails, or is completing asynchronously, the return /// value is zero(FALSE). To get extended error information, call the GetLastError function. /// [DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] [PInvokeData("FileAPI.h", MSDNShortId = "aa365467")] public static extern unsafe bool ReadFile(HFILE hFile, byte* lpBuffer, uint nNumberOfBytesToRead, IntPtr lpNumberOfBytesRead, NativeOverlapped* lpOverlapped); /// /// Reads data from the specified file or input/output (I/O) device. Reads occur at the position specified by the file pointer if /// supported by the device. /// /// /// A handle to the device (for example, a file, file stream, physical disk, volume, console buffer, tape drive, socket, /// communications resource, mailslot, or pipe). The hFile parameter must have been created with read access. /// /// A pointer to the buffer that receives the data read from a file or device. /// The maximum number of bytes to be read. /// /// A pointer to the variable that receives the number of bytes read when using a synchronous hFile parameter. ReadFile sets this /// value to zero before doing any work or error checking. Use NULL for this parameter if this is an asynchronous operation to avoid /// potentially erroneous results. /// This parameter can be NULL only when the lpOverlapped parameter is not NULL. /// /// /// A pointer to an OVERLAPPED structure is required if the hFile parameter was opened with FILE_FLAG_OVERLAPPED, otherwise it can be NULL. /// /// If hFile is opened with FILE_FLAG_OVERLAPPED, the lpOverlapped parameter must point to a valid and unique OVERLAPPED structure, /// otherwise the function can incorrectly report that the read operation is complete. /// /// /// For an hFile that supports byte offsets, if you use this parameter you must specify a byte offset at which to start reading from /// the file or device. This offset is specified by setting the Offset and OffsetHigh members of the OVERLAPPED structure. For an /// hFile that does not support byte offsets, Offset and OffsetHigh are ignored. /// /// /// For more information about different combinations of lpOverlapped and FILE_FLAG_OVERLAPPED, see the Remarks section and the /// Synchronization and File Position section. /// /// /// /// If the function succeeds, the return value is nonzero (TRUE). If the function fails, or is completing asynchronously, the return /// value is zero(FALSE). To get extended error information, call the GetLastError function. /// [DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] [PInvokeData("FileAPI.h", MSDNShortId = "aa365467")] public static extern bool ReadFile(HFILE hFile, byte[] lpBuffer, uint nNumberOfBytesToRead, out uint lpNumberOfBytesRead, [Optional] IntPtr lpOverlapped); /// /// /// Reads data from the specified file or input/output (I/O) device. It reports its completion status asynchronously, calling the /// specified completion routine when reading is completed or canceled and the calling thread is in an alertable wait state. /// /// To read data from a file or device synchronously, use the ReadFile function. /// /// /// /// A handle to the file or I/O device (for example, a file, file stream, physical disk, volume, console buffer, tape drive, socket, /// communications resource, mailslot, or pipe). /// /// /// This parameter can be any handle opened with the FILE_FLAG_OVERLAPPED flag by the CreateFile function, or a socket /// handle returned by the socket or accept function. /// /// /// This handle also must have the GENERIC_READ access right. For more information on access rights, see File Security and /// Access Rights. /// /// /// /// A pointer to a buffer that receives the data read from the file or device. /// /// This buffer must remain valid for the duration of the read operation. The application should not use this buffer until the read /// operation is completed. /// /// /// /// The number of bytes to be read. /// /// /// /// A pointer to an OVERLAPPED data structure that supplies data to be used during the asynchronous (overlapped) file read operation. /// /// /// For files that support byte offsets, you must specify a byte offset at which to start reading from the file. You specify this /// offset by setting the Offset and OffsetHigh members of the OVERLAPPED structure. For files or devices that /// do not support byte offsets, Offset and OffsetHigh are ignored. /// /// /// The ReadFileEx function ignores the OVERLAPPED structure's hEvent member. An application is free to use that /// member for its own purposes in the context of a ReadFileEx call. ReadFileEx signals completion of its read /// operation by calling, or queuing a call to, the completion routine pointed to by lpCompletionRoutine, so it does not need an /// event handle. /// /// /// The ReadFileEx function does use the OVERLAPPED structure's Internal and InternalHigh members. An /// application should not set these members. /// /// /// The OVERLAPPED data structure must remain valid for the duration of the read operation. It should not be a variable that /// can go out of scope while the read operation is pending completion. /// /// /// /// /// A pointer to the completion routine to be called when the read operation is complete and the calling thread is in an alertable /// wait state. For more information about the completion routine, see FileIOCompletionRoutine. /// /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// /// If the function succeeds, the calling thread has an asynchronous I/O operation pending: the overlapped read operation from the /// file. When this I/O operation completes, and the calling thread is blocked in an alertable wait state, the system calls the /// function pointed to by lpCompletionRoutine, and the wait state completes with a return code of WAIT_IO_COMPLETION. /// /// /// If the function succeeds, and the file reading operation completes, but the calling thread is not in an alertable wait state, the /// system queues the completion routine call, holding the call until the calling thread enters an alertable wait state. For /// information about alertable waits and overlapped input/output operations, see About Synchronization. /// /// /// If ReadFileEx attempts to read past the end-of-file (EOF), the call to GetOverlappedResult for that operation /// returns FALSE and GetLastError returns ERROR_HANDLE_EOF. /// /// // BOOL WINAPI ReadFileEx( _In_ HANDLE hFile, _Out_opt_ LPVOID lpBuffer, _In_ DWORD nNumberOfBytesToRead, _Inout_ LPOVERLAPPED // lpOverlapped, _In_ LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("FileAPI.h", MSDNShortId = "aa365468")] [return: MarshalAs(UnmanagedType.Bool)] public static extern unsafe bool ReadFileEx([In] HFILE hFile, byte* lpBuffer, uint nNumberOfBytesToRead, NativeOverlapped* lpOverlapped, FileIOCompletionRoutineUnsafe lpCompletionRoutine); /// /// Reads data from a file and stores it in an array of buffers. /// /// The function starts reading data from the file at a position that is specified by an OVERLAPPED structure. The /// ReadFileScatter function operates asynchronously. /// /// /// /// A handle to the file to be read. /// /// The file handle must be created with the GENERIC_READ right, and the FILE_FLAG_OVERLAPPED and /// FILE_FLAG_NO_BUFFERING flags. For more information, see File Security and Access Rights. /// /// /// /// /// A pointer to an array of FILE_SEGMENT_ELEMENT buffers that receives the data. For a description of this union, see Remarks. /// /// Each element can receive one page of data. /// /// The array must contain enough elements to store nNumberOfBytesToRead bytes of data, plus one element for the terminating /// NULL. For example, if there are 40 KB to be read and the page size is 4 KB, the array must have 11 elements that includes /// 10 for the data and one for the NULL. /// /// /// Each buffer must be at least the size of a system memory page and must be aligned on a system memory page size boundary. The /// system reads one system memory page of data into each buffer. /// /// /// The function stores the data in the buffers in sequential order. For example, it stores data into the first buffer, then into the /// second buffer, and so on until each buffer is filled and all the data is stored, or there are no more buffers. /// /// /// /// /// The total number of bytes to be read from the file. Each element of aSegmentArray contains a one-page chunk of this total. /// Because the file must be opened with FILE_FLAG_NO_BUFFERING, the number of bytes must be a multiple of the sector size of /// the file system where the file is located. /// /// /// /// This parameter is reserved for future use and must be NULL. /// /// /// A pointer to an OVERLAPPED data structure. /// /// The ReadFileScatter function requires a valid OVERLAPPED structure. The lpOverlapped parameter cannot be NULL. /// /// /// The ReadFileScatter function starts reading data from the file at a position that is specified by the Offset and /// OffsetHigh members of the OVERLAPPED structure. /// /// /// The ReadFileScatter function may return before the read operation is complete. In that scenario, the /// ReadFileScatter function returns the value 0 (zero), and the GetLastError function returns the value /// ERROR_IO_PENDING. This asynchronous operation of ReadFileScatter lets the calling process continue while the read /// operation completes. You can call the GetOverlappedResult, HasOverlappedIoCompleted, or /// GetQueuedCompletionStatus functions to obtain information about the completion of the read operation. For more /// information, see Synchronous and Asynchronous I/O. /// /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero (0). To get extended error information, call the GetLastError function. /// /// If ReadFileScatter attempts to read past the end-of-file (EOF), the call to GetOverlappedResult for that operation /// returns FALSE and GetLastError returns ERROR_HANDLE_EOF. /// /// /// If the function returns before the read operation is complete, the function returns zero (0), and GetLastError returns ERROR_IO_PENDING. /// /// // BOOL WINAPI ReadFileScatter( _In_ HANDLE hFile, _In_ FILE_SEGMENT_ELEMENT aSegmentArray[], _In_ DWORD nNumberOfBytesToRead, // _Reserved_ LPDWORD lpReserved, _Inout_ LPOVERLAPPED lpOverlapped); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("FileAPI.h", MSDNShortId = "aa365469")] [return: MarshalAs(UnmanagedType.Bool)] public static extern unsafe bool ReadFileScatter([In] HFILE hFile, [In] IntPtr aSegmentArray, uint nNumberOfBytesToRead, IntPtr lpReserved, NativeOverlapped* lpOverlapped); /// /// Deletes an existing empty directory. /// To perform this operation as a transacted operation, use the RemoveDirectoryTransacted function. /// /// /// /// The path of the directory to be removed. This path must specify an empty directory, and the calling process must have delete /// access to the directory. /// /// /// In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to 32,767 wide /// characters, call the Unicode version of the function and prepend "\\?\" to the path. For more information, see Naming a File. /// /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// // BOOL WINAPI RemoveDirectory( _In_ LPCTSTR lpPathName); [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [PInvokeData("FileAPI.h", MSDNShortId = "aa365488")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool RemoveDirectory(string lpPathName); /// /// Sets the physical file size for the specified file to the current position of the file pointer. /// /// The physical file size is also referred to as the end of the file. The SetEndOfFile function can be used to truncate or /// extend a file. To set the logical end of a file, use the SetFileValidData function. /// /// /// /// A handle to the file to be extended or truncated. /// /// The file handle must be created with the GENERIC_WRITE access right. For more information, see File Security and Access Rights. /// /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero (0). To get extended error information, call GetLastError. /// // BOOL WINAPI SetEndOfFile( _In_ HANDLE hFile); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("FileAPI.h", MSDNShortId = "aa365531")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetEndOfFile([In] HFILE hFile); /// /// Sets the attributes for a file or directory. /// To perform this operation as a transacted operation, use the SetFileAttributesTransacted function. /// /// /// The name of the file whose attributes are to be set. /// /// In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to 32,767 wide /// characters, call the Unicode version of the function ( SetFileAttributesW) and prepend "\\?\" to the path. For more /// information, see File Names, Paths, and Namespaces. /// /// /// /// The file attributes to set for the file. /// This parameter can be one or more values, combined using the bitwise-OR operator. However, all other values override FILE_ATTRIBUTE_NORMAL. /// Not all attributes are supported by this function. For more information, see the Remarks section. /// The following is a list of supported attribute values. /// /// /// /// Value /// Meaning /// /// /// FILE_ATTRIBUTE_ARCHIVE = 32 (0x20) /// /// A file or directory that is an archive file or directory. Applications typically use this attribute to mark files for backup or removal. /// /// /// /// FILE_ATTRIBUTE_HIDDEN = 2 (0x2) /// The file or directory is hidden. It is not included in an ordinary directory listing. /// /// /// FILE_ATTRIBUTE_NORMAL = 128 (0x80) /// A file that does not have other attributes set. This attribute is valid only when used alone. /// /// /// FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = 8192 (0x2000) /// The file or directory is not to be indexed by the content indexing service. /// /// /// FILE_ATTRIBUTE_OFFLINE = 4096 (0x1000) /// /// The data of a file is not available immediately. This attribute indicates that the file data is physically moved to offline /// storage. This attribute is used by Remote Storage, which is the hierarchical storage management software. Applications should not /// arbitrarily change this attribute. /// /// /// /// FILE_ATTRIBUTE_READONLY = 1 (0x1) /// /// A file that is read-only. Applications can read the file, but cannot write to it or delete it. This attribute is not honored on /// directories. For more information, see &quot;You cannot view or change the Read-only or the System attributes of folders in /// Windows Server 2003, in Windows XP, or in Windows Vista. /// /// /// /// FILE_ATTRIBUTE_SYSTEM = 4 (0x4) /// A file or directory that the operating system uses a part of, or uses exclusively. /// /// /// FILE_ATTRIBUTE_TEMPORARY = 256 (0x100) /// /// A file that is being used for temporary storage. File systems avoid writing data back to mass storage if sufficient cache memory /// is available, because typically, an application deletes a temporary file after the handle is closed. In that scenario, the system /// can entirely avoid writing the data. Otherwise, the data is written after the handle is closed. /// /// /// /// /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// // BOOL WINAPI SetFileAttributes( _In_ LPCTSTR lpFileName, _In_ DWORD dwFileAttributes); [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [PInvokeData("FileAPI.h", MSDNShortId = "aa365535")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetFileAttributes(string lpFileName, FileFlagsAndAttributes dwFileAttributes); /// /// Sets the file information for the specified file. /// To retrieve file information using a file handle, see GetFileInformationByHandle or GetFileInformationByHandleEx. /// /// /// A handle to the file for which to change information. /// /// This handle must be opened with the appropriate permissions for the requested change. For more information, see the Remarks and /// Example Code sections. /// /// This handle should not be a pipe handle. /// /// /// A FILE_INFO_BY_HANDLE_CLASS enumeration value that specifies the type of information to be changed. /// For a table of valid values, see the Remarks section. /// /// /// /// A pointer to the buffer that contains the information to change for the specified file information class. The structure that this /// parameter points to corresponds to the class that is specified by FileInformationClass. /// /// For a table of valid structure types, see the Remarks section. /// /// /// The size of lpFileInformation, in bytes. /// /// /// Returns nonzero if successful or zero otherwise. /// To get extended error information, call GetLastError. /// // BOOL WINAPI SetFileInformationByHandle( _In_ HANDLE hFile, _In_ FILE_INFO_BY_HANDLE_CLASS FileInformationClass, _In_ LPVOID // lpFileInformation, _In_ DWORD dwBufferSize); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("FileAPI.h", MSDNShortId = "aa365539")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetFileInformationByHandle([In] HFILE hFile, FILE_INFO_BY_HANDLE_CLASS FileInformationClass, SafeAllocatedMemoryHandle lpFileInformation, uint dwBufferSize); /// /// Sets the file information for the specified file. /// To retrieve file information using a file handle, see GetFileInformationByHandle or GetFileInformationByHandleEx. /// /// /// A handle to the file for which to change information. /// /// This handle must be opened with the appropriate permissions for the requested change. For more information, see the Remarks and /// Example Code sections. /// /// This handle should not be a pipe handle. /// /// /// A FILE_INFO_BY_HANDLE_CLASS enumeration value that specifies the type of information to be changed. /// For a table of valid values, see the Remarks section. /// /// /// /// The buffer that contains the information to change for the specified file information class. The structure that this parameter /// points to corresponds to the class that is specified by FileInformationClass. /// /// For a table of valid structure types, see the Remarks section. /// /// /// Returns if successful or otherwise. /// To get extended error information, call GetLastError. /// public static bool SetFileInformationByHandle([In] HFILE hFile, FILE_INFO_BY_HANDLE_CLASS FileInformationClass, T lpFileInformation) where T : struct { if (!CorrespondingTypeAttribute.CanSet(FileInformationClass, typeof(T))) throw new InvalidOperationException("Type mismatch."); using (var mem = SafeHGlobalHandle.CreateFromStructure(lpFileInformation)) return SetFileInformationByHandle(hFile, FileInformationClass, mem, (uint)mem.Size); } /// /// Moves the file pointer of the specified file. /// /// This function stores the file pointer in two LONG values. To work with file pointers that are larger than a single /// LONG value, it is easier to use the SetFilePointerEx function. /// /// /// /// A handle to the file. /// /// The file handle must be created with the GENERIC_READ or GENERIC_WRITE access right. For more information, see File /// Security and Access Rights. /// /// /// /// The low order 32-bits of a signed value that specifies the number of bytes to move the file pointer. /// /// If lpDistanceToMoveHigh is not NULL, lpDistanceToMoveHigh and lDistanceToMove form a single 64-bit signed value that /// specifies the distance to move. /// /// /// If lpDistanceToMoveHigh is NULL, lDistanceToMove is a 32-bit signed value. A positive value for lDistanceToMove moves the /// file pointer forward in the file, and a negative value moves the file pointer back. /// /// /// /// A pointer to the high order 32-bits of the signed 64-bit distance to move. /// If you do not need the high order 32-bits, this pointer must be set to NULL. /// /// When not NULL, this parameter also receives the high order DWORD of the new value of the file pointer. For more /// information, see the Remarks section in this topic. /// /// /// /// The starting point for the file pointer move. /// This parameter can be one of the following values. /// /// /// /// Value /// Meaning /// /// /// FILE_BEGIN = 0 /// The starting point is zero or the beginning of the file. /// /// /// FILE_CURRENT = 1 /// The starting point is the current value of the file pointer. /// /// /// FILE_END = 2 /// The starting point is the current end-of-file position. /// /// /// /// /// /// /// If the function succeeds and lpDistanceToMoveHigh is NULL, the return value is the low-order DWORD of the new file pointer. /// /// /// Note If the function returns a value other than INVALID_SET_FILE_POINTER, the call to SetFilePointer has /// succeeded. You do not need to call GetLastError. /// /// /// If function succeeds and lpDistanceToMoveHigh is not NULL, the return value is the low-order DWORD of the new file /// pointer and lpDistanceToMoveHigh contains the high order DWORD of the new file pointer. /// /// If the function fails, the return value is INVALID_SET_FILE_POINTER. To get extended error information, call GetLastError. /// /// If a new file pointer is a negative value, the function fails, the file pointer is not moved, and the code returned by /// GetLastError is ERROR_NEGATIVE_SEEK. /// /// /// If lpDistanceToMoveHigh is NULL and the new file position does not fit in a 32-bit value, the function fails and returns INVALID_SET_FILE_POINTER. /// /// // DWORD WINAPI SetFilePointer( _In_ HANDLE hFile, _In_ LONG lDistanceToMove, _Inout_opt_ PLONG lpDistanceToMoveHigh, _In_ DWORD dwMoveMethod); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("FileAPI.h", MSDNShortId = "aa365541")] public static extern uint SetFilePointer([In] HFILE hFile, int lDistanceToMove, ref int lpDistanceToMoveHigh, SeekOrigin dwMoveMethod); /// /// Moves the file pointer of the specified file. /// /// /// /// A handle to the file. The file handle must have been created with the GENERIC_READ or GENERIC_WRITE access right. /// For more information, see File Security and Access Rights. /// /// /// /// /// The number of bytes to move the file pointer. A positive value moves the pointer forward in the file and a negative value moves /// the file pointer backward. /// /// /// /// /// A pointer to a variable to receive the new file pointer. If this parameter is NULL, the new file pointer is not returned. /// /// /// /// The starting point for the file pointer move. This parameter can be one of the following values. /// /// /// Value /// Meaning /// /// /// FILE_BEGIN = 0 /// /// The starting point is zero or the beginning of the file. If this flag is specified, then the liDistanceToMove parameter is /// interpreted as an unsigned value. /// /// /// /// FILE_CURRENT = 1 /// The start point is the current value of the file pointer. /// /// /// FILE_END = 2 /// The starting point is the current end-of-file position. /// /// /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// // BOOL WINAPI SetFilePointerEx( _In_ HANDLE hFile, _In_ LARGE_INTEGER liDistanceToMove, _Out_opt_ PLARGE_INTEGER lpNewFilePointer, // _In_ DWORD dwMoveMethod); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("FileAPI.h", MSDNShortId = "aa365542")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetFilePointerEx([In] HFILE hFile, long liDistanceToMove, out long lpNewFilePointer, SeekOrigin dwMoveMethod); /// /// Sets the date and time that the specified file or directory was created, last accessed, or last modified. /// /// /// /// A handle to the file or directory. The handle must have been created using the CreateFile function with the /// FILE_WRITE_ATTRIBUTES access right. For more information, see File Security and Access Rights. /// /// /// /// /// A pointer to a FILETIME structure that contains the new creation date and time for the file or directory. If the /// application does not need to change this information, set this parameter either to NULL or to a pointer to a /// FILETIME structure that has both the dwLowDateTime and dwHighDateTime members set to 0. /// /// /// /// /// A pointer to a FILETIME structure that contains the new last access date and time for the file or directory. The last /// access time includes the last time the file or directory was written to, read from, or (in the case of executable files) run. If /// the application does not need to change this information, set this parameter either to NULL or to a pointer to a /// FILETIME structure that has both the dwLowDateTime and dwHighDateTime members set to 0. /// /// /// To prevent file operations using the given handle from modifying the last access time, call SetFileTime immediately after /// opening the file handle and pass a FILETIME structure that has both the dwLowDateTime and dwHighDateTime /// members set to 0xFFFFFFFF. /// /// /// /// /// A pointer to a FILETIME structure that contains the new last modified date and time for the file or directory. If the /// application does not need to change this information, set this parameter either to NULL or to a pointer to a /// FILETIME structure that has both the dwLowDateTime and dwHighDateTime members set to 0. /// /// /// To prevent file operations using the given handle from modifying the last access time, call SetFileTime immediately after /// opening the file handle and pass a FILETIME structure that has both the dwLowDateTime and dwHighDateTime /// members set to 0xFFFFFFFF. /// /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// // BOOL WINAPI SetFileTime( _In_ HANDLE hFile, _In_opt_ const FILETIME *lpCreationTime, _In_opt_ const FILETIME *lpLastAccessTime, // _In_opt_ const FILETIME *lpLastWriteTime); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("FileAPI.h", MSDNShortId = "ms724933")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetFileTime([In] HFILE hFile, in FILETIME lpCreationTime, in FILETIME lpLastAccessTime, in FILETIME lpLastWriteTime); /// /// Sets the date and time that the specified file or directory was created, last accessed, or last modified. /// /// /// /// A handle to the file or directory. The handle must have been created using the CreateFile function with the /// FILE_WRITE_ATTRIBUTES access right. For more information, see File Security and Access Rights. /// /// /// /// /// A pointer to a FILETIME structure that contains the new creation date and time for the file or directory. If the /// application does not need to change this information, set this parameter either to NULL or to a pointer to a /// FILETIME structure that has both the dwLowDateTime and dwHighDateTime members set to 0. /// /// /// /// /// A pointer to a FILETIME structure that contains the new last access date and time for the file or directory. The last /// access time includes the last time the file or directory was written to, read from, or (in the case of executable files) run. If /// the application does not need to change this information, set this parameter either to NULL or to a pointer to a /// FILETIME structure that has both the dwLowDateTime and dwHighDateTime members set to 0. /// /// /// To prevent file operations using the given handle from modifying the last access time, call SetFileTime immediately after /// opening the file handle and pass a FILETIME structure that has both the dwLowDateTime and dwHighDateTime /// members set to 0xFFFFFFFF. /// /// /// /// /// A pointer to a FILETIME structure that contains the new last modified date and time for the file or directory. If the /// application does not need to change this information, set this parameter either to NULL or to a pointer to a /// FILETIME structure that has both the dwLowDateTime and dwHighDateTime members set to 0. /// /// /// To prevent file operations using the given handle from modifying the last access time, call SetFileTime immediately after /// opening the file handle and pass a FILETIME structure that has both the dwLowDateTime and dwHighDateTime /// members set to 0xFFFFFFFF. /// /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// // BOOL WINAPI SetFileTime( _In_ HANDLE hFile, _In_opt_ const FILETIME *lpCreationTime, _In_opt_ const FILETIME *lpLastAccessTime, // _In_opt_ const FILETIME *lpLastWriteTime); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("FileAPI.h", MSDNShortId = "ms724933")] [return: MarshalAs(UnmanagedType.Bool)] public static extern unsafe bool SetFileTime([In] HFILE hFile, [In, Optional] FILETIME* lpCreationTime, [In, Optional] FILETIME* lpLastAccessTime, [In, Optional] FILETIME* lpLastWriteTime); /// /// Sets the valid data length of the specified file. This function is useful in very limited scenarios. For more information, see /// the Remarks section. /// /// /// /// A handle to the file. The file must have been opened with the GENERIC_WRITE access right, and the /// SE_MANAGE_VOLUME_NAME privilege enabled. For more information, see File Security and Access Rights. /// /// Note The file cannot be a network file, or be compressed, sparse, or transacted. /// /// /// The new valid data length. /// /// This parameter must be a positive value that is greater than the current valid data length, but less than the current file size. /// /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is 0. To get extended error information, call GetLastError. /// /// /// /// The SetFileValidData function sets the logical end of a file. To set the size of a file, use the SetEndOfFile function. /// The physical file size is also referred to as the end of the file. /// /// Each file stream has the following properties: /// /// /// File size: the size of the data in a file, to the byte. /// /// /// /// Allocation size: the size of the space that is allocated for a file on a disk, which is always an even multiple of the cluster size. /// /// /// /// /// Valid data length: the length of the data in a file that is actually written, to the byte. This value is always less than or /// equal to the file size. /// /// /// /// /// Typically, the SetFileValidData function is used by system-level applications on their own private data. Not all file /// systems use valid data length. Some file systems can track multiple valid data ranges. In general, most applications will never /// need to call this function. /// /// /// The SetFileValidData function allows you to avoid filling data with zeros when writing nonsequentially to a file. The /// function makes the data in the file valid without writing to the file. As a result, although some performance gain may be /// realized, existing data on disk from previously existing files can inadvertently become available to unintended readers. The /// following paragraphs provide a more detailed description of this potential security and privacy issue. /// /// /// A caller must have the SE_MANAGE_VOLUME_NAME privilege enabled when opening a file initially. Applications should call /// SetFileValidData only on files that restrict access to those entities that have SE_MANAGE_VOLUME_NAME access. The /// application must ensure that the unwritten ranges of the file are never exposed, or security issues can result as follows. /// /// /// If SetFileValidData is used on a file, the potential performance gain is obtained by not filling the allocated clusters /// for the file with zeros. Therefore, reading from the file will return whatever the allocated clusters contain, potentially /// content from other users. This is not necessarily a security issue at this point, because the caller needs to have /// SE_MANAGE_VOLUME_NAME privilege for SetFileValidData to succeed, and all data on disk can be read by such users. /// However, this caller can inadvertently expose this data to other users that cannot acquire the SE_MANAGE_VOLUME_PRIVILEGE /// privilege if the following holds: /// /// /// /// /// If the file was not opened with a sharing mode that denies other readers, a nonprivileged user can open it and read the exposed data. /// /// /// /// /// If the system stops responding before the caller finishes writing up the ValidDataLength supplied in the call, then, on a reboot, /// such a nonprivileged user can open the file and read exposed content. /// /// /// /// /// If the caller of SetFileValidData opened the file with adequately restrictive access control, the previous conditions /// would not apply. However, for partially written files extended with SetFileValidData (that is, writing was not completed /// up to the ValidDataLength supplied in the call) there exists yet another potential privacy or security vulnerability. An /// administrator could copy the file to a target that is not properly controlled with restrictive ACL permissions, thus /// inadvertently exposing the extended area's data to unauthorized reading. /// /// /// It is for these reasons that SetFileValidData is not recommended for general purpose use, in addition to performance /// considerations, as discussed below. /// /// /// For more information about security and access privileges, see Running with Special Privileges and File Security and Access Rights. /// /// /// You can use the SetFileValidData function to create large files in very specific circumstances so that the performance of /// subsequent file I/O can be better than other methods. Specifically, if the extended portion of the file is large and will be /// written to randomly, such as in a database type of application, the time it takes to extend and write to the file will be faster /// than using SetEndOfFile and writing randomly. In most other situations, there is usually no performance gain to using /// SetFileValidData, and sometimes there can be a performance penalty. /// /// In Windows 8 and Windows Server 2012, this function is supported by the following technologies. /// /// /// Technology /// Supported /// /// /// Server Message Block (SMB) 3.0 protocol /// Yes /// /// /// SMB 3.0 Transparent Failover (TFO) /// Yes /// /// /// SMB 3.0 with Scale-out File Shares (SO) /// Yes /// /// /// Cluster Shared Volume File System (CsvFS) /// Yes /// /// /// Resilient File System (ReFS) /// Yes /// /// /// // https://docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-setfilevaliddata BOOL SetFileValidData( HANDLE hFile, // LONGLONG ValidDataLength ); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("fileapi.h", MSDNShortId = "c6ded2d7-270a-4b75-b2d4-1007a92fe831")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetFileValidData([In] HFILE hFile, long ValidDataLength); /// /// Unlocks a region in an open file. Unlocking a region enables other processes to access the region. /// For an alternate way to specify the region, use the UnlockFileEx function. /// /// /// /// A handle to the file that contains a region locked with LockFile. The file handle must have been created with either the /// GENERIC_READ or GENERIC_WRITE access right. For more information, see File Security and Access Rights. /// /// /// /// The low-order word of the starting byte offset in the file where the locked region begins. /// /// /// The high-order word of the starting byte offset in the file where the locked region begins. /// /// /// The low-order word of the length of the byte range to be unlocked. /// /// /// The high-order word of the length of the byte range to be unlocked. /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// // BOOL WINAPI UnlockFile( _In_ HANDLE hFile, _In_ DWORD dwFileOffsetLow, _In_ DWORD dwFileOffsetHigh, _In_ DWORD // nNumberOfBytesToUnlockLow, _In_ DWORD nNumberOfBytesToUnlockHigh); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("FileAPI.h", MSDNShortId = "aa365715")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool UnlockFile([In] HFILE hFile, uint dwFileOffsetLow, uint dwFileOffsetHigh, uint nNumberOfBytesToUnlockLow, uint nNumberOfBytesToUnlockHigh); /// /// Unlocks a region in the specified file. This function can operate either synchronously or asynchronously. /// /// /// /// A handle to the file. The handle must have been created with either the GENERIC_READ or GENERIC_WRITE access right. /// For more information, see File Security and Access Rights. /// /// /// /// Reserved parameter; must be zero. /// /// /// The low-order part of the length of the byte range to unlock. /// /// /// The high-order part of the length of the byte range to unlock. /// /// /// /// A pointer to an OVERLAPPED structure that the function uses with the unlocking request. This structure contains the file /// offset of the beginning of the unlock range. You must initialize the hEvent member to a valid handle or zero. For more /// information, see Synchronous and Asynchronous I/O. /// /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero or NULL. To get extended error information, call GetLastError. /// // BOOL WINAPI UnlockFileEx( _In_ HANDLE hFile, _Reserved_ DWORD dwReserved, _In_ DWORD nNumberOfBytesToUnlockLow, _In_ DWORD // nNumberOfBytesToUnlockHigh, _Inout_ LPOVERLAPPED lpOverlapped); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("FileAPI.h", MSDNShortId = "aa365716")] [return: MarshalAs(UnmanagedType.Bool)] public static extern unsafe bool UnlockFileEx([In] HFILE hFile, uint dwReserved, uint nNumberOfBytesToUnlockLow, uint nNumberOfBytesToUnlockHigh, NativeOverlapped* lpOverlapped); /// /// Writes data to the specified file or input/output (I/O) device. /// /// This function is designed for both synchronous and asynchronous operation. For a similar function designed solely for /// asynchronous operation, see WriteFileEx. /// /// /// /// A handle to the file or I/O device (for example, a file, file stream, physical disk, volume, console buffer, tape drive, socket, /// communications resource, mailslot, or pipe). /// /// The hFile parameter must have been created with the write access. For more information, see Generic Access Rights and File /// Security and Access Rights. /// /// /// For asynchronous write operations, hFile can be any handle opened with the CreateFile function using the FILE_FLAG_OVERLAPPED /// flag or a socket handle returned by the socket or accept function. /// /// /// /// A pointer to the buffer containing the data to be written to the file or device. /// /// This buffer must remain valid for the duration of the write operation. The caller must not use this buffer until the write /// operation is completed. /// /// /// /// The number of bytes to be written to the file or device. /// /// A value of zero specifies a null write operation. The behavior of a null write operation depends on the underlying file system or /// communications technology. /// /// /// Windows Server 2003 and Windows XP: Pipe write operations across a network are limited in size per write. The amount varies per /// platform. For x86 platforms it's 63.97 MB. For x64 platforms it's 31.97 MB. For Itanium it's 63.95 MB. For more information /// regarding pipes, see the Remarks section. /// /// /// /// A pointer to the variable that receives the number of bytes written when using a synchronous hFile parameter. WriteFile sets this /// value to zero before doing any work or error checking. Use NULL for this parameter if this is an asynchronous operation to avoid /// potentially erroneous results. /// This parameter can be NULL only when the lpOverlapped parameter is not NULL. /// For more information, see the Remarks section. /// /// /// A pointer to an OVERLAPPED structure is required if the hFile parameter was opened with FILE_FLAG_OVERLAPPED, otherwise this /// parameter can be NULL. /// /// For an hFile that supports byte offsets, if you use this parameter you must specify a byte offset at which to start writing to /// the file or device. This offset is specified by setting the Offset and OffsetHigh members of the OVERLAPPED structure. For an /// hFile that does not support byte offsets, Offset and OffsetHigh are ignored. /// /// /// To write to the end of file, specify both the Offset and OffsetHigh members of the OVERLAPPED structure as 0xFFFFFFFF. This is /// functionally equivalent to previously calling the CreateFile function to open hFile using FILE_APPEND_DATA access. /// /// /// For more information about different combinations of lpOverlapped and FILE_FLAG_OVERLAPPED, see the Remarks section and the /// Synchronization and File Position section. /// /// /// /// If the function succeeds, the return value is nonzero (TRUE). If the function fails, or is completing asynchronously, the return /// value is zero(FALSE). To get extended error information, call the GetLastError function. /// [DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] [PInvokeData("FileAPI.h", MSDNShortId = "aa365747")] public static extern bool WriteFile(HFILE hFile, IntPtr lpBuffer, uint nNumberOfBytesToWrite, out uint lpNumberOfBytesWritten, [Optional] IntPtr lpOverlapped); /// /// Writes data to the specified file or input/output (I/O) device. /// /// This function is designed for both synchronous and asynchronous operation. For a similar function designed solely for /// asynchronous operation, see WriteFileEx. /// /// /// /// A handle to the file or I/O device (for example, a file, file stream, physical disk, volume, console buffer, tape drive, socket, /// communications resource, mailslot, or pipe). /// /// The hFile parameter must have been created with the write access. For more information, see Generic Access Rights and File /// Security and Access Rights. /// /// /// For asynchronous write operations, hFile can be any handle opened with the CreateFile function using the FILE_FLAG_OVERLAPPED /// flag or a socket handle returned by the socket or accept function. /// /// /// /// A pointer to the buffer containing the data to be written to the file or device. /// /// This buffer must remain valid for the duration of the write operation. The caller must not use this buffer until the write /// operation is completed. /// /// /// /// The number of bytes to be written to the file or device. /// /// A value of zero specifies a null write operation. The behavior of a null write operation depends on the underlying file system or /// communications technology. /// /// /// Windows Server 2003 and Windows XP: Pipe write operations across a network are limited in size per write. The amount varies per /// platform. For x86 platforms it's 63.97 MB. For x64 platforms it's 31.97 MB. For Itanium it's 63.95 MB. For more information /// regarding pipes, see the Remarks section. /// /// /// /// A pointer to the variable that receives the number of bytes written when using a synchronous hFile parameter. WriteFile sets this /// value to zero before doing any work or error checking. Use NULL for this parameter if this is an asynchronous operation to avoid /// potentially erroneous results. /// This parameter can be NULL only when the lpOverlapped parameter is not NULL. /// For more information, see the Remarks section. /// /// /// A pointer to an OVERLAPPED structure is required if the hFile parameter was opened with FILE_FLAG_OVERLAPPED, otherwise this /// parameter can be NULL. /// /// For an hFile that supports byte offsets, if you use this parameter you must specify a byte offset at which to start writing to /// the file or device. This offset is specified by setting the Offset and OffsetHigh members of the OVERLAPPED structure. For an /// hFile that does not support byte offsets, Offset and OffsetHigh are ignored. /// /// /// To write to the end of file, specify both the Offset and OffsetHigh members of the OVERLAPPED structure as 0xFFFFFFFF. This is /// functionally equivalent to previously calling the CreateFile function to open hFile using FILE_APPEND_DATA access. /// /// /// For more information about different combinations of lpOverlapped and FILE_FLAG_OVERLAPPED, see the Remarks section and the /// Synchronization and File Position section. /// /// /// /// If the function succeeds, the return value is nonzero (TRUE). If the function fails, or is completing asynchronously, the return /// value is zero(FALSE). To get extended error information, call the GetLastError function. /// [DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] [PInvokeData("FileAPI.h", MSDNShortId = "aa365747")] public static extern unsafe bool WriteFile(HFILE hFile, byte* lpBuffer, uint nNumberOfBytesToWrite, [Optional] uint* lpNumberOfBytesWritten, [Optional] NativeOverlapped* lpOverlapped); /// /// Writes data to the specified file or input/output (I/O) device. /// /// This function is designed for both synchronous and asynchronous operation. For a similar function designed solely for /// asynchronous operation, see WriteFileEx. /// /// /// /// A handle to the file or I/O device (for example, a file, file stream, physical disk, volume, console buffer, tape drive, socket, /// communications resource, mailslot, or pipe). /// /// The hFile parameter must have been created with the write access. For more information, see Generic Access Rights and File /// Security and Access Rights. /// /// /// For asynchronous write operations, hFile can be any handle opened with the CreateFile function using the FILE_FLAG_OVERLAPPED /// flag or a socket handle returned by the socket or accept function. /// /// /// /// A pointer to the buffer containing the data to be written to the file or device. /// /// This buffer must remain valid for the duration of the write operation. The caller must not use this buffer until the write /// operation is completed. /// /// /// /// The number of bytes to be written to the file or device. /// /// A value of zero specifies a null write operation. The behavior of a null write operation depends on the underlying file system or /// communications technology. /// /// /// Windows Server 2003 and Windows XP: Pipe write operations across a network are limited in size per write. The amount varies per /// platform. For x86 platforms it's 63.97 MB. For x64 platforms it's 31.97 MB. For Itanium it's 63.95 MB. For more information /// regarding pipes, see the Remarks section. /// /// /// /// A pointer to the variable that receives the number of bytes written when using a synchronous hFile parameter. WriteFile sets this /// value to zero before doing any work or error checking. Use NULL for this parameter if this is an asynchronous operation to avoid /// potentially erroneous results. /// This parameter can be NULL only when the lpOverlapped parameter is not NULL. /// For more information, see the Remarks section. /// /// /// A pointer to an OVERLAPPED structure is required if the hFile parameter was opened with FILE_FLAG_OVERLAPPED, otherwise this /// parameter can be NULL. /// /// For an hFile that supports byte offsets, if you use this parameter you must specify a byte offset at which to start writing to /// the file or device. This offset is specified by setting the Offset and OffsetHigh members of the OVERLAPPED structure. For an /// hFile that does not support byte offsets, Offset and OffsetHigh are ignored. /// /// /// To write to the end of file, specify both the Offset and OffsetHigh members of the OVERLAPPED structure as 0xFFFFFFFF. This is /// functionally equivalent to previously calling the CreateFile function to open hFile using FILE_APPEND_DATA access. /// /// /// For more information about different combinations of lpOverlapped and FILE_FLAG_OVERLAPPED, see the Remarks section and the /// Synchronization and File Position section. /// /// /// /// If the function succeeds, the return value is nonzero (TRUE). If the function fails, or is completing asynchronously, the return /// value is zero(FALSE). To get extended error information, call the GetLastError function. /// [DllImport(Lib.Kernel32, ExactSpelling = true, SetLastError = true), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] [PInvokeData("FileAPI.h", MSDNShortId = "aa365747")] public static extern bool WriteFile(HFILE hFile, byte[] lpBuffer, uint nNumberOfBytesToWrite, out uint lpNumberOfBytesWritten, [Optional] IntPtr lpOverlapped); /// /// /// Writes data to the specified file or input/output (I/O) device. It reports its completion status asynchronously, calling the /// specified completion routine when writing is completed or canceled and the calling thread is in an alertable wait state. /// /// To write data to a file or device synchronously, use the WriteFile function. /// /// /// /// A handle to the file or I/O device (for example, a file, file stream, physical disk, volume, console buffer, tape drive, socket, /// communications resource, mailslot, or pipe). /// /// /// This parameter can be any handle opened with the FILE_FLAG_OVERLAPPED flag by the CreateFile function, or a socket /// handle returned by the socket or accept function. /// /// Do not associate an I/O completion port with this handle. For more information, see the Remarks section. /// /// This handle also must have the GENERIC_WRITE access right. For more information on access rights, see File Security and /// Access Rights. /// /// /// /// A pointer to the buffer containing the data to be written to the file or device. /// /// This buffer must remain valid for the duration of the write operation. The caller must not use this buffer until the write /// operation is completed. /// /// /// /// The number of bytes to be written to the file or device. /// /// A value of zero specifies a null write operation. The behavior of a null write operation depends on the underlying file system. /// /// /// Pipe write operations across a network are limited to 65,535 bytes per write. For more information regarding pipes, see the /// Remarks section. /// /// /// /// /// A pointer to an OVERLAPPED data structure that supplies data to be used during the overlapped (asynchronous) write operation. /// /// /// For files that support byte offsets, you must specify a byte offset at which to start writing to the file. You specify this /// offset by setting the Offset and OffsetHigh members of the OVERLAPPED structure. For files or devices that /// do not support byte offsets, Offset and OffsetHigh are ignored. /// /// /// To write to the end of file, specify both the Offset and OffsetHigh members of the OVERLAPPED structure as /// 0xFFFFFFFF. This is functionally equivalent to previously calling the CreateFile function to open hFile using /// FILE_APPEND_DATA access. /// /// /// The WriteFileEx function ignores the OVERLAPPED structure's hEvent member. An application is free to use /// that member for its own purposes in the context of a WriteFileEx call. WriteFileEx signals completion of its /// writing operation by calling, or queuing a call to, the completion routine pointed to by lpCompletionRoutine, so it does not need /// an event handle. /// /// /// The WriteFileEx function does use the Internal and InternalHigh members of the OVERLAPPED structure. /// You should not change the value of these members. /// /// /// The OVERLAPPED data structure must remain valid for the duration of the write operation. It should not be a variable that /// can go out of scope while the write operation is pending completion. /// /// /// /// /// A pointer to a completion routine to be called when the write operation has been completed and the calling thread is in an /// alertable wait state. For more information about this completion routine, see FileIOCompletionRoutine. /// /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// /// If the WriteFileEx function succeeds, the calling thread has an asynchronous I/O operation pending: the overlapped write /// operation to the file. When this I/O operation finishes, and the calling thread is blocked in an alertable wait state, the /// operating system calls the function pointed to by lpCompletionRoutine, and the wait completes with a return code of WAIT_IO_COMPLETION. /// /// /// If the function succeeds and the file-writing operation finishes, but the calling thread is not in an alertable wait state, the /// system queues the call to *lpCompletionRoutine, holding the call until the calling thread enters an alertable wait state. For /// more information about alertable wait states and overlapped input/output operations, see About Synchronization. /// /// // BOOL WINAPI WriteFileEx( _In_ HANDLE hFile, _In_opt_ LPCVOID lpBuffer, _In_ DWORD nNumberOfBytesToWrite, _Inout_ LPOVERLAPPED // lpOverlapped, _In_ LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("FileAPI.h", MSDNShortId = "aa365748")] [return: MarshalAs(UnmanagedType.Bool)] public static extern unsafe bool WriteFileEx([In] HFILE hFile, [In] byte* lpBuffer, uint nNumberOfBytesToWrite, NativeOverlapped* lpOverlapped, FileIOCompletionRoutineUnsafe lpCompletionRoutine); /// /// Retrieves data from an array of buffers and writes the data to a file. /// /// The function starts writing data to the file at a position that is specified by an OVERLAPPED structure. The /// WriteFileGather function operates asynchronously. /// /// /// /// /// A handle to the file. The file handle must be created with the GENERIC_WRITE access right, and the /// FILE_FLAG_OVERLAPPED and FILE_FLAG_NO_BUFFERING flags. For more information, see File Security and Access Rights. /// /// /// /// /// A pointer to an array of FILE_SEGMENT_ELEMENT buffers that contain the data. For a description of this union, see Remarks. /// /// Each element contains the address of one page of data. /// /// Each buffer must be at least the size of a system memory page and must be aligned on a system memory page size boundary. The /// system writes one system memory page of data from each buffer. /// /// /// The function gathers the data from the buffers in a sequential order. For example, it writes data to the file from the first /// buffer, then the second buffer, and so on until there is no more data. /// /// /// Due to the asynchronous operation of this function, precautions must be taken to ensure that this parameter always references /// valid memory for the lifetime of the asynchronous writes. For instance, a common programming error is to use local stack storage /// and then allow execution to run out of scope. /// /// /// /// /// The total number of bytes to be written. Each element of aSegmentArray contains a one-page chunk of this total. Because the file /// must be opened with FILE_FLAG_NO_BUFFERING, the number of bytes must be a multiple of the sector size of the file system /// where the file is located. /// /// /// If nNumberOfBytesToWrite is zero (0), the function performs a null write operation. The behavior of a null write operation /// depends on the underlying file system. If nNumberOfBytesToWrite is not zero (0) and the offset and length of the write place data /// beyond the current end of the file, the WriteFileGather function extends the file. /// /// /// /// This parameter is reserved for future use and must be NULL. /// /// /// A pointer to an OVERLAPPED data structure. /// /// The WriteFileGather function requires a valid OVERLAPPED structure. The lpOverlapped parameter cannot be NULL. /// /// /// The WriteFileGather function starts writing data to the file at a position that is specified by the Offset and /// OffsetHigh members of the OVERLAPPED structure. /// /// /// The WriteFileGather function may return before the write operation is complete. In that scenario, the /// WriteFileGather function returns the value zero (0), and the GetLastError function returns the value /// ERROR_IO_PENDING. This asynchronous operation of the WriteFileGather function lets the calling process continue /// while the write operation completes. You can call the GetOverlappedResult, HasOverlappedIoCompleted, or /// GetQueuedCompletionStatus function to obtain information about the completion of the write operation. For more /// information, see Synchronous and Asynchronous I/O. /// /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero (0). To get extended error information, call the GetLastError function. /// /// If the function returns before the write operation is complete, the function returns zero (0), and the GetLastError /// function returns ERROR_IO_PENDING. /// /// // BOOL WINAPI WriteFileGather( _In_ HANDLE hFile, _In_ FILE_SEGMENT_ELEMENT aSegmentArray[], _In_ DWORD nNumberOfBytesToWrite, // _Reserved_ LPDWORD lpReserved, _Inout_ LPOVERLAPPED lpOverlapped); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("FileAPI.h", MSDNShortId = "aa365749")] [return: MarshalAs(UnmanagedType.Bool)] public static extern unsafe bool WriteFileGather([In] HFILE hFile, [In] IntPtr aSegmentArray, uint nNumberOfBytesToWrite, IntPtr lpReserved, NativeOverlapped* lpOverlapped); /// /// /// Retrieves information about MS-DOS device names. The function can obtain the current mapping for a particular MS-DOS device name. /// The function can also obtain a list of all existing MS-DOS device names. /// /// /// MS-DOS device names are stored as junctions in the object namespace. The code that converts an MS-DOS path into a corresponding /// path uses these junctions to map MS-DOS devices and drive letters. The QueryDosDevice function enables an application to /// query the names of the junctions used to implement the MS-DOS device namespace as well as the value of each specific junction. /// /// /// /// /// An MS-DOS device name string specifying the target of the query. The device name cannot have a trailing backslash; for example, /// use "C:", not "C:\". /// /// /// This parameter can be NULL. In that case, the QueryDosDevice function will store a list of all existing MS-DOS /// device names into the buffer pointed to by lpTargetPath. /// /// /// /// /// A pointer to a buffer that will receive the result of the query. The function fills this buffer with one or more null-terminated /// strings. The final null-terminated string is followed by an additional NULL. /// /// /// If lpDeviceName is non- NULL, the function retrieves information about the particular MS-DOS device specified by /// lpDeviceName. The first null-terminated string stored into the buffer is the current mapping for the device. The other /// null-terminated strings represent undeleted prior mappings for the device. /// /// /// If lpDeviceName is NULL, the function retrieves a list of all existing MS-DOS device names. Each null-terminated string /// stored into the buffer is the name of an existing MS-DOS device, for example, \Device\HarddiskVolume1 or \Device\Floppy0. /// /// /// /// The maximum number of TCHARs that can be stored into the buffer pointed to by lpTargetPath. /// /// /// If the function succeeds, the return value is the number of TCHARs stored into the buffer pointed to by lpTargetPath. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// If the buffer is too small, the function fails and the last error code is ERROR_INSUFFICIENT_BUFFER. /// // DWORD WINAPI QueryDosDevice( _In_opt_ LPCTSTR lpDeviceName, _Out_ LPTSTR lpTargetPath, _In_ DWORD ucchMax); [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [PInvokeData("FileAPI.h", MSDNShortId = "aa365461")] private static extern uint QueryDosDevice(string lpDeviceName, IntPtr lpTargetPath, int ucchMax); /// Contains information that the GetFileInformationByHandle function retrieves. [StructLayout(LayoutKind.Sequential)] [PInvokeData("FileAPI.h", MSDNShortId = "aa363788")] public struct BY_HANDLE_FILE_INFORMATION { /// The file attributes. For possible values and their descriptions, see File Attribute Constants. public FileFlagsAndAttributes dwFileAttributes; /// /// A FILETIME structure that specifies when a file or directory is created. If the underlying file system does not support /// creation time, this member is zero (0). /// public FILETIME ftCreationTime; /// /// A FILETIME structure. For a file, the structure specifies the last time that a file is read from or written to. For a /// directory, the structure specifies when the directory is created. For both files and directories, the specified date is /// correct, but the time of day is always set to midnight. If the underlying file system does not support the last access time, /// this member is zero (0). /// public FILETIME ftLastAccessTime; /// /// A FILETIME structure. For a file, the structure specifies the last time that a file is written to. For a directory, the /// structure specifies when the directory is created. If the underlying file system does not support the last write time, this /// member is zero (0). /// public FILETIME ftLastWriteTime; /// The serial number of the volume that contains a file. public uint dwVolumeSerialNumber; /// The high-order part of the file size. public uint nFileSizeHigh; /// The low-order part of the file size. public uint nFileSizeLow; /// /// The number of links to this file. For the FAT file system this member is always 1. For the NTFS file system, it can be more /// than 1. /// public uint nNumberOfLinks; /// The high-order part of a unique identifier that is associated with a file. For more information, see nFileIndexLow. public uint nFileIndexHigh; /// /// The low-order part of a unique identifier that is associated with a file. /// /// The identifier (low and high parts) and the volume serial number uniquely identify a file on a single computer. To determine /// whether two open handles represent the same file, combine the identifier and the volume serial number for each file and /// compare them. /// /// /// The ReFS file system, introduced with Windows Server 2012, includes 128-bit file identifiers. To retrieve the 128-bit file /// identifier use the GetFileInformationByHandleEx function with FileIdInfo to retrieve the FILE_ID_INFO structure. The 64-bit /// identifier in this structure is not guaranteed to be unique on ReFS. /// /// public uint nFileIndexLow; } /// /// Contains optional extended parameters for CreateFile2. /// // typedef struct _CREATEFILE2_EXTENDED_PARAMETERS { DWORD dwSize; DWORD dwFileAttributes; DWORD dwFileFlags; DWORD // dwSecurityQosFlags; LPSECURITY_ATTRIBUTES lpSecurityAttributes; HANDLE hTemplateFile;} CREATEFILE2_EXTENDED_PARAMETERS, // *PCREATEFILE2_EXTENDED_PARAMETERS, *LPCREATEFILE2_EXTENDED_PARAMETERS; [PInvokeData("FileAPI.h", MSDNShortId = "hh449426")] [StructLayout(LayoutKind.Sequential)] public struct CREATEFILE2_EXTENDED_PARAMETERS { /// /// Contains the size of this structure, . /// public uint dwSize; /// /// The file or device attributes and flags, FILE_ATTRIBUTE_NORMAL being the most common default value for files. /// /// This parameter can include any combination of the available file attributes ( FILE_ATTRIBUTE_*). All other file /// attributes override FILE_ATTRIBUTE_NORMAL. /// /// /// Some of the following file attributes and flags may only apply to files and not necessarily all other types of devices that /// CreateFile2 can open. For additional information, see the Remarks section of the CreateFile2 reference page and /// Creating and Opening Files. /// /// /// For more advanced access to file attributes, see SetFileAttributes. For a complete list of all file attributes with /// their values and descriptions, see File Attribute Constants. /// /// /// /// /// Attribute /// Meaning /// /// /// FILE_ATTRIBUTE_ARCHIVE32 (0x20) /// The file should be archived. Applications use this attribute to mark files for backup or removal. /// /// /// FILE_ATTRIBUTE_ENCRYPTED16384 (0x4000) /// /// The file or directory is encrypted. For a file, this means that all data in the file is encrypted. For a directory, this /// means that encryption is the default for newly created files and subdirectories. For more information, see File /// Encryption.This flag has no effect if FILE_ATTRIBUTE_SYSTEM is also specified.This flag is not supported on Home, Home /// Premium, Starter, or ARM editions of Windows.This flag is not supported when called from a Windows Store app. /// /// /// /// FILE_ATTRIBUTE_HIDDEN2 (0x2) /// The file is hidden. Do not include it in an ordinary directory listing. /// /// /// FILE_ATTRIBUTE_INTEGRITY_STREAM32768 (0x8000) /// /// A file or directory that is configured with integrity. For a file, all data streams in the file have integrity. For a /// directory, integrity is the default for newly created files and subdirectories, unless the caller specifies otherwise.This /// flag is only supported on the ReFS file system. /// /// /// /// FILE_ATTRIBUTE_NORMAL128 (0x80) /// The file does not have other attributes set. This attribute is valid only if used alone. /// /// /// FILE_ATTRIBUTE_OFFLINE4096 (0x1000) /// /// The data of a file is not immediately available. This attribute indicates that file data is physically moved to offline /// storage. This attribute is used by Remote Storage, the hierarchical storage management software. Applications should not /// arbitrarily change this attribute. /// /// /// /// FILE_ATTRIBUTE_READONLY1 (0x1) /// The file is read only. Applications can read the file, but cannot write to or delete it. /// /// /// FILE_ATTRIBUTE_SYSTEM4 (0x4) /// The file is part of or used exclusively by an operating system. /// /// /// FILE_ATTRIBUTE_TEMPORARY256 (0x100) /// The file is being used for temporary storage.For more information, see the Caching Behavior section of this topic. /// /// /// /// public FileFlagsAndAttributes dwFileAttributes; /// /// /// This parameter can contain combinations of flags ( FILE_FLAG_*) for control of file or device caching behavior, access /// modes, and other special-purpose flags. /// /// /// /// /// Flag /// Meaning /// /// /// FILE_FLAG_BACKUP_SEMANTICS0x02000000 /// /// The file is being opened or created for a backup or restore operation. The system ensures that the calling process overrides /// file security checks when the process has SE_BACKUP_NAME and SE_RESTORE_NAME privileges. For more information, see Changing /// Privileges in a Token.You must set this flag to obtain a handle to a directory. A directory handle can be passed to some /// functions instead of a file handle. For more information, see the Remarks section. /// /// /// /// FILE_FLAG_DELETE_ON_CLOSE0x04000000 /// /// The file is to be deleted immediately after all of its handles are closed, which includes the specified handle and any other /// open or duplicated handles.If there are existing open handles to a file, the call fails unless they were all opened with the /// FILE_SHARE_DELETE share mode.Subsequent open requests for the file fail, unless the FILE_SHARE_DELETE share mode is specified. /// /// /// /// FILE_FLAG_NO_BUFFERING0x20000000 /// /// The file or device is being opened with no system caching for data reads and writes. This flag does not affect hard disk /// caching or memory mapped files.There are strict requirements for successfully working with files opened with CreateFile2 /// using the FILE_FLAG_NO_BUFFERING flag, for details see File Buffering. /// /// /// /// FILE_FLAG_OPEN_NO_RECALL0x00100000 /// /// The file data is requested, but it should continue to be located in remote storage. It should not be transported back to /// local storage. This flag is for use by remote storage systems. /// /// /// /// FILE_FLAG_OPEN_REPARSE_POINT0x00200000 /// /// Normal reparse point processing will not occur; CreateFile2 will attempt to open the reparse point. When a file is opened, a /// file handle is returned, whether or not the filter that controls the reparse point is operational.This flag cannot be used /// with the CREATE_ALWAYS flag.If the file is not a reparse point, then this flag is ignored.For more information, see the /// Remarks section. /// /// /// /// FILE_FLAG_OPEN_REQUIRING_OPLOCK0x00040000 /// /// The file is being opened and an opportunistic lock (oplock) on the file is being requested as a single atomic operation. The /// file system checks for oplocks before it performs the create operation, and will fail the create with a last error code of /// ERROR_CANNOT_BREAK_OPLOCK if the result would be to break an existing oplock.If you use this flag and your call to the /// CreateFile2 function successfully returns, the first operation you should perform on the file handle is to request an oplock /// by calling the DeviceIOControl function and then pass in FSCTL_REQUEST_OPLOCK or one of the other Opportunistic Lock /// Operations. If you perform other file system operations with the file handle before requesting an oplock, a deadlock might occur. /// /// /// /// FILE_FLAG_OVERLAPPED0x40000000 /// /// The file or device is being opened or created for asynchronous I/O.When subsequent I/O operations are completed on this /// handle, the event specified in the OVERLAPPED structure will be set to the signaled state.If this flag is specified, the file /// can be used for simultaneous read and write operations.If this flag is not specified, then I/O operations are serialized, /// even if the calls to the read and write functions specify an OVERLAPPED structure.For information about considerations when /// using a file handle created with this flag, see the Synchronous and Asynchronous I/O Handles section of this topic. /// /// /// /// FILE_FLAG_POSIX_SEMANTICS0x0100000 /// /// Access will occur according to POSIX rules. This includes allowing multiple files with names, differing only in case, for /// file systems that support that naming. Use care when using this option, because files created with this flag may not be /// accessible by applications that are written for MS-DOS or 16-bit Windows. /// /// /// /// FILE_FLAG_RANDOM_ACCESS0x10000000 /// /// Access is intended to be random. The system can use this as a hint to optimize file caching.This flag has no effect if the /// file system does not support cached I/O and FILE_FLAG_NO_BUFFERING.For more information, see the Caching Behavior section of /// this topic. /// /// /// /// FILE_FLAG_SESSION_AWARE0x00800000 /// /// The file or device is being opened with session awareness. If this flag is not specified, then per-session devices (such as a /// device using RemoteFX USB Redirection) cannot be opened by processes running in session 0. This flag has no effect for /// callers not in session 0. This flag is supported only on server editions of Windows.Windows Server 2008 R2 and Windows Server /// 2008: This flag is not supported before Windows Server 2012. /// /// /// /// FILE_FLAG_SEQUENTIAL_SCAN0x08000000 /// /// Access is intended to be sequential from beginning to end. The system can use this as a hint to optimize file caching.This /// flag should not be used if read-behind (that is, backwards scans) will be used.This flag has no effect if the file system /// does not support cached I/O and FILE_FLAG_NO_BUFFERING.For more information, see the Caching Behavior section of this topic. /// /// /// /// FILE_FLAG_WRITE_THROUGH0x80000000 /// /// Write operations will not go through any intermediate cache, they will go directly to disk.For additional information, see /// the Caching Behavior section of this topic. /// /// /// /// /// public FileFlagsAndAttributes dwFileFlags; /// /// The dwSecurityQosFlags parameter specifies SQOS information. For more information, see Impersonation Levels. /// /// /// /// Security flag /// Meaning /// /// /// SECURITY_ANONYMOUS /// Impersonates a client at the Anonymous impersonation level. /// /// /// SECURITY_CONTEXT_TRACKING /// The security tracking mode is dynamic. If this flag is not specified, the security tracking mode is static. /// /// /// SECURITY_DELEGATION /// Impersonates a client at the Delegation impersonation level. /// /// /// SECURITY_EFFECTIVE_ONLY /// /// Only the enabled aspects of the client's security context are available to the server. If you do not specify this flag, all /// aspects of the client's security context are available.This allows the client to limit the groups and privileges that a /// server can use while impersonating the client. /// /// /// /// SECURITY_IDENTIFICATION /// Impersonates a client at the Identification impersonation level. /// /// /// SECURITY_IMPERSONATION /// Impersonate a client at the impersonation level. This is the default behavior if no other flags are specified. /// /// /// /// public FileFlagsAndAttributes dwSecurityQosFlags; /// /// /// A pointer to a SECURITY_ATTRIBUTES structure that contains two separate but related data members: an optional security /// descriptor, and a Boolean value that determines whether the returned handle can be inherited by child processes. /// /// This parameter can be NULL. /// /// If this parameter is NULL, the handle returned by CreateFile2 cannot be inherited by any child processes the /// application may create and the file or device associated with the returned handle gets a default security descriptor. /// /// /// The lpSecurityDescriptor member of the structure specifies a SECURITY_DESCRIPTOR for a file or device. If this /// member is NULL, the file or device associated with the returned handle is assigned a default security descriptor. /// /// /// CreateFile2 ignores the lpSecurityDescriptor member when opening an existing file or device, but continues to /// use the bInheritHandle member. /// /// The bInheritHandle member of the structure specifies whether the returned handle can be inherited. /// For more information, see the Remarks section of the CreateFile2 topic. /// public IntPtr lpSecurityAttributes; /// /// /// A valid handle to a template file with the GENERIC_READ access right. The template file supplies file attributes and /// extended attributes for the file that is being created. /// /// This parameter can be NULL. /// When opening an existing file, CreateFile2 ignores this parameter. /// /// When opening a new encrypted file, the file inherits the discretionary access control list from its parent directory. For /// additional information, see File Encryption. /// /// public HFILE hTemplateFile; } /// Represents a self-closing change notification handle created by the FindFirstChangeNotification function. public class SafeFindChangeNotificationHandle : SafeSyncHandle { /// Initializes a new instance of the class. /// The handle. public SafeFindChangeNotificationHandle(IntPtr handle) : base(handle) { } private SafeFindChangeNotificationHandle() : base() { } /// protected override bool InternalReleaseHandle() => FindCloseChangeNotification(handle); } /// Provides a that releases a created HFILE instance at disposal using CloseHandle. public class SafeHFILE : SafeKernelHandle { /// Initializes a new instance of the class and assigns an existing handle. /// An object that represents the pre-existing handle to use. /// /// to reliably release the handle during the finalization phase; otherwise, (not recommended). /// public SafeHFILE(IntPtr preexistingHandle, bool ownsHandle = true) : base(preexistingHandle, ownsHandle) { } /// Initializes a new instance of the class. protected SafeHFILE() : base() { } /// Performs an implicit conversion from to . /// The safe handle instance. /// The result of the conversion. public static explicit operator SafeHFILE(Microsoft.Win32.SafeHandles.SafeFileHandle h) => new SafeHFILE(h.DangerousGetHandle(), false); /// Performs an implicit conversion from to . /// The safe handle instance. /// The result of the conversion. public static implicit operator HFILE(SafeHFILE h) => h.handle; } /// /// Represents a self-closing file search handle opened by the FindFirstFile, FindFirstFileEx, FindFirstFileNameW, /// FindFirstFileNameTransactedW, FindFirstFileTransacted, FindFirstStreamTransactedW, or FindFirstStreamW functions. /// /// public class SafeSearchHandle : SafeHANDLE { /// Initializes a new instance of the class. /// The handle. public SafeSearchHandle(IntPtr handle) : base(handle) { } private SafeSearchHandle() : base() { } /// protected override bool InternalReleaseHandle() => FindClose(handle); } /// Represents a self-closing volume search handle opened by the FindFirstVolume. /// public class SafeVolumeSearchHandle : SafeHANDLE { /// Initializes a new instance of the class. /// The handle. public SafeVolumeSearchHandle(IntPtr handle) : base(handle) { } private SafeVolumeSearchHandle() : base() { } /// protected override bool InternalReleaseHandle() => FindVolumeClose(handle); } } }