using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using Vanara.InteropServices;
using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME;
namespace Vanara.PInvoke
{
public static partial class Kernel32
{
///
/// An application-defined callback function used with the CopyFileEx, MoveFileTransacted, and MoveFileWithProgress functions. It is
/// called when a portion of a copy or move operation is completed. The LPPROGRESS_ROUTINE type defines a pointer to this callback function.
/// CopyProgressRoutine is a placeholder for the application-defined function name.
///
/// The total size of the file, in bytes.
///
/// The total number of bytes transferred from the source file to the destination file since the copy operation began.
///
/// The total size of the current file stream, in bytes.
///
/// The total number of bytes in the current stream that have been transferred from the source file to the destination file since the copy operation began.
///
/// A handle to the current stream. The first time CopyProgressRoutine is called, the stream number is 1.
///
/// The reason that CopyProgressRoutine was called. This parameter can be one of the following values.
///
///
///
/// Value
/// Meaning
///
/// -
/// CALLBACK_CHUNK_FINISHED0x00000000
/// Another part of the data file was copied.
///
/// -
/// CALLBACK_STREAM_SWITCH0x00000001
/// Another stream was created and is about to be copied. This is the callback reason given when the callback routine is first invoked.
///
///
///
///
/// A handle to the source file.
/// A handle to the destination file
/// Argument passed to CopyProgressRoutine by CopyFileEx, MoveFileTransacted, or MoveFileWithProgress.
///
/// The CopyProgressRoutine function should return one of the following values.
///
///
///
/// Return code/value
/// Description
///
/// -
/// PROGRESS_CANCEL1
/// Cancel the copy operation and delete the destination file.
///
/// -
/// PROGRESS_CONTINUE0
/// Continue the copy operation.
///
/// -
/// PROGRESS_QUIET3
/// Continue the copy operation, but stop invoking CopyProgressRoutine to report progress.
///
/// -
/// PROGRESS_STOP2
/// Stop the copy operation. It can be restarted at a later time.
///
///
///
///
// DWORD CALLBACK CopyProgressRoutine( _In_ LARGE_INTEGER TotalFileSize, _In_ LARGE_INTEGER TotalBytesTransferred, _In_ LARGE_INTEGER StreamSize, _In_
// LARGE_INTEGER StreamBytesTransferred, _In_ DWORD dwStreamNumber, _In_ DWORD dwCallbackReason, _In_ HANDLE hSourceFile, _In_ HANDLE hDestinationFile,
// _In_opt_ LPVOID lpData);typedef DWORD (WINAPI *LPPROGRESS_ROUTINE)( _In_ LARGE_INTEGER TotalFileSize, _In_ LARGE_INTEGER TotalBytesTransferred, _In_
// LARGE_INTEGER StreamSize, _In_ LARGE_INTEGER StreamBytesTransferred, _In_ DWORD dwStreamNumber, _In_ DWORD dwCallbackReason, _In_ HANDLE hSourceFile,
// _In_ HANDLE hDestinationFile, _In_opt_ LPVOID lpData); https://msdn.microsoft.com/en-us/library/windows/desktop/aa363854(v=vs.85).aspx
[UnmanagedFunctionPointer(CallingConvention.Winapi)]
[PInvokeData("WinBase.h", MSDNShortId = "aa363854")]
public delegate uint CopyProgressRoutine(long TotalFileSize, long TotalBytesTransferred, long StreamSize, long StreamBytesTransferred, uint dwStreamNumber, COPY_CALLBACK_REASON dwCallbackReason, [In] IntPtr hSourceFile, [In] IntPtr hDestinationFile, [In] IntPtr lpData);
/// The reason that CopyProgressRoutine was called.
public enum COPY_CALLBACK_REASON : uint
{
/// Another part of the data file was copied.
CALLBACK_CHUNK_FINISHED = 0x00000000,
/// Another stream was created and is about to be copied. This is the callback reason given when the callback routine is first invoked.
CALLBACK_STREAM_SWITCH = 0x00000001,
}
/// Flags used by .
[PInvokeData("winbase.h", MSDNShortId = "a8da62e5-bc49-4aff-afaa-e774393b7120")]
[Flags]
public enum COPY_FILE : uint
{
/// The copy will be attempted even if the destination file cannot be encrypted.
COPY_FILE_ALLOW_DECRYPTED_DESTINATION = 0x00000008,
///
/// If the source file is a symbolic link, the destination file is also a symbolic link pointing to the same file as the source
/// symbolic link.
///
COPY_FILE_COPY_SYMLINK = 0x00000800,
///
/// If the destination file exists the copy operation fails immediately. If a file or directory exists with the destination name
/// then the CopyFile2 function call will fail with either HRESULT_FROM_WIN32(ERROR_ALREADY_EXISTS) or
/// HRESULT_FROM_WIN32(ERROR_FILE_EXISTS). If COPY_FILE_RESUME_FROM_PAUSE is also specified then a failure is only triggered if
/// the destination file does not have a valid restart header.
///
COPY_FILE_FAIL_IF_EXISTS = 0x00000001,
///
/// The copy is performed using unbuffered I/O, bypassing the system cache resources. This flag is recommended for very large
/// file copies. It is not recommended to pause copies that are using this flag.
///
COPY_FILE_NO_BUFFERING = 0x00001000,
/// Do not attempt to use the Windows Copy Offload mechanism. This is not generally recommended.
COPY_FILE_NO_OFFLOAD = 0x00040000,
/// The file is copied and the source file is opened for write access.
COPY_FILE_OPEN_SOURCE_FOR_WRITE = 0x00000004,
///
/// The file is copied in a manner that can be restarted if the same source and destination filenames are used again. This is slower.
///
COPY_FILE_RESTARTABLE = 0x00000002,
///
/// The copy is attempted, specifying ACCESS_SYSTEM_SECURITY for the source file and ACCESS_SYSTEM_SECURITY | WRITE_DAC |
/// WRITE_OWNER for the destination file. If these requests are denied the access request will be reduced to the highest
/// privilege level for which access is granted. For more information see SACL Access Right. This can be used to allow the
/// CopyFile2ProgressRoutine callback to perform operations requiring higher privileges, such as copying the security attributes
/// for the file.
///
COPY_FILE_REQUEST_SECURITY_PRIVILEGES = 0x00002000,
///
/// The destination file is examined to see if it was copied using COPY_FILE_RESTARTABLE. If so the copy is resumed. If not the
/// file will be fully copied.
///
COPY_FILE_RESUME_FROM_PAUSE = 0x00004000,
/// Undocumented.
COPY_FILE_IGNORE_EDP_BLOCK = 0x00400000,
/// Undocumented.
COPY_FILE_IGNORE_SOURCE_ENCRYPTION = 0x00800000,
}
///
///
/// Identifies the type of file information that GetFileInformationByHandleEx should retrieve or SetFileInformationByHandle should set.
///
///
// typedef enum _FILE_INFO_BY_HANDLE_CLASS { FileBasicInfo = 0, FileStandardInfo = 1, FileNameInfo = 2, FileRenameInfo = 3, FileDispositionInfo = 4,
// FileAllocationInfo = 5, FileEndOfFileInfo = 6, FileStreamInfo = 7, FileCompressionInfo = 8, FileAttributeTagInfo = 9, FileIdBothDirectoryInfo = 10, //
// 0xA FileIdBothDirectoryRestartInfo = 11, // 0xB FileIoPriorityHintInfo = 12, // 0xC FileRemoteProtocolInfo = 13, // 0xD FileFullDirectoryInfo = 14, //
// 0xE FileFullDirectoryRestartInfo = 15, // 0xF FileStorageInfo = 16, // 0x10 FileAlignmentInfo = 17, // 0x11 FileIdInfo = 18, // 0x12
// FileIdExtdDirectoryInfo = 19, // 0x13 FileIdExtdDirectoryRestartInfo = 20, // 0x14 MaximumFileInfoByHandlesClass} FILE_INFO_BY_HANDLE_CLASS, *PFILE_INFO_BY_HANDLE_CLASS;
[PInvokeData("WinBase.h", MSDNShortId = "aa364228")]
public enum FILE_INFO_BY_HANDLE_CLASS
{
///
/// Minimal information for the file should be retrieved or set. Used for file handles. See FILE_BASIC_INFO.
///
FileBasicInfo = 0,
///
///
/// Extended information for the file should be retrieved. Used for file handles. Use only when calling GetFileInformationByHandleEx. See FILE_STANDARD_INFO.
///
///
FileStandardInfo,
///
/// The file name should be retrieved. Used for any handles. Use only when calling GetFileInformationByHandleEx. See FILE_NAME_INFO.
///
FileNameInfo,
///
/// The file name should be changed. Used for file handles. Use only when calling SetFileInformationByHandle. See FILE_RENAME_INFO.
///
FileRenameInfo,
///
/// The file should be deleted. Used for any handles. Use only when calling SetFileInformationByHandle. See FILE_DISPOSITION_INFO.
///
FileDispositionInfo,
///
///
/// The file allocation information should be changed. Used for file handles. Use only when calling SetFileInformationByHandle. See FILE
/// ALLOCATION INFO.
///
///
FileAllocationInfo,
///
/// The end of the file should be set. Use only when calling SetFileInformationByHandle. See FILE_END_OF_FILE_INFO.
///
FileEndOfFileInfo,
///
///
/// File stream information for the specified file should be retrieved. Used for any handles. Use only when calling
/// GetFileInformationByHandleEx. See FILE_STREAM_INFO.
///
///
FileStreamInfo,
///
///
/// File compression information should be retrieved. Used for any handles. Use only when calling GetFileInformationByHandleEx. See FILE_COMPRESSION_INFO.
///
///
FileCompressionInfo,
///
/// File attribute information should be retrieved. Used for any handles. Use only when calling GetFileInformationByHandleEx. See FILE_ATTRIBUTE_TAG_INFO.
///
FileAttributeTagInfo,
///
///
/// Files in the specified directory should be retrieved. Used for directory handles. Use only when calling GetFileInformationByHandleEx. The
/// number of files returned for each call to GetFileInformationByHandleEx depends on the size of the buffer that is passed to the function.
/// Any subsequent calls to GetFileInformationByHandleEx on the same handle will resume the enumeration operation after the last file is
/// returned. See FILE_ID_BOTH_DIR_INFO.
///
///
FileIdBothDirectoryInfo,
///
/// Identical to FileIdBothDirectoryInfo, but forces the enumeration operation to start again from the beginning. See FILE_ID_BOTH_DIR_INFO.
///
FileIdBothDirectoryRestartInfo,
///
/// Priority hint information should be set. Use only when calling SetFileInformationByHandle. See FILE_IO_PRIORITY_HINT_INFO.
///
FileIoPriorityHintInfo,
///
///
/// File remote protocol information should be retrieved. Use for any handles. Use only when calling GetFileInformationByHandleEx. See FILE_REMOTE_PROTOCOL_INFO.
///
///
FileRemoteProtocolInfo,
///
///
/// Files in the specified directory should be retrieved. Used for directory handles. Use only when calling GetFileInformationByHandleEx. See FILE_FULL_DIR_INFO.
///
///
/// Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003 and Windows XP: This value is not supported
/// before Windows 8 and Windows Server 2012
///
///
FileFullDirectoryInfo,
///
///
/// Identical to FileFullDirectoryInfo, but forces the enumeration operation to start again from the beginning. Use only when calling
/// GetFileInformationByHandleEx. See FILE_FULL_DIR_INFO.
///
///
/// Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003 and Windows XP: This value is not supported
/// before Windows 8 and Windows Server 2012
///
///
FileFullDirectoryRestartInfo,
///
/// File storage information should be retrieved. Use for any handles. Use only when calling GetFileInformationByHandleEx. See FILE_STORAGE_INFO.
///
/// Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003 and Windows XP: This value is not supported
/// before Windows 8 and Windows Server 2012
///
///
FileStorageInfo,
///
/// File alignment information should be retrieved. Use for any handles. Use only when calling GetFileInformationByHandleEx. See FILE_ALIGNMENT_INFO.
///
/// Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003 and Windows XP: This value is not supported
/// before Windows 8 and Windows Server 2012
///
///
FileAlignmentInfo,
///
/// File information should be retrieved. Use for any handles. Use only when calling GetFileInformationByHandleEx. See FILE_ID_INFO.
///
/// Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003 and Windows XP: This value is not supported
/// before Windows 8 and Windows Server 2012
///
///
FileIdInfo,
///
///
/// Files in the specified directory should be retrieved. Used for directory handles. Use only when calling GetFileInformationByHandleEx. See FILE_ID_EXTD_DIR_INFO.
///
///
/// Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003 and Windows XP: This value is not supported
/// before Windows 8 and Windows Server 2012
///
///
FileIdExtdDirectoryInfo,
///
///
/// Identical to FileIdExtdDirectoryInfo, but forces the enumeration operation to start again from the beginning. Use only when calling
/// GetFileInformationByHandleEx. See FILE_ID_EXTD_DIR_INFO.
///
///
/// Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003 and Windows XP: This value is not supported
/// before Windows 8 and Windows Server 2012
///
///
FileIdExtdDirectoryRestartInfo,
///
/// This value is used for validation. Supported values are less than this value.
///
MaximumFileInfoByHandlesClass,
}
/// The type of result to return.
[PInvokeData("WinBase.h")]
[Flags]
public enum FinalPathNameOptions
{
/// Return the path with the drive letter. This is the default.
VOLUME_NAME_DOS = 0x0,
/// Return the path with a volume GUID path instead of the drive name.
VOLUME_NAME_GUID = 0x1,
/// Return the path with the volume device path.
VOLUME_NAME_NT = 0x2,
/// Return the path with no drive information.
VOLUME_NAME_NONE = 0x4,
/// Return the normalized drive name. This is the default.
FILE_NAME_NORMALIZED = 0x0,
/// Return the opened file name (not normalized).
FILE_NAME_OPENED = 0x8,
}
/// MoveFileEx options.
[Flags]
public enum MOVEFILE : uint
{
///
/// If a file named lpNewFileName exists, the function replaces its contents with the contents of the lpExistingFileName file, provided that security
/// requirements regarding access control lists (ACLs) are met. For more information, see the Remarks section of this topic.This value cannot be used
/// if lpNewFileName or lpExistingFileName names a directory.
///
MOVEFILE_REPLACE_EXISTING = 0x00000001,
///
/// If the file is to be moved to a different volume, the function simulates the move by using the CopyFile and DeleteFile functions.If the file is
/// successfully copied to a different volume and the original file is unable to be deleted, the function succeeds leaving the source file
/// intact.This value cannot be used with MOVEFILE_DELAY_UNTIL_REBOOT.
///
MOVEFILE_COPY_ALLOWED = 0x00000002,
///
/// The system does not move the file until the operating system is restarted. The system moves the file immediately after AUTOCHK is executed, but
/// before creating any paging files. Consequently, this parameter enables the function to delete paging files from previous startups.This value can
/// be used only if the process is in the context of a user who belongs to the administrators group or the LocalSystem account. This value cannot be
/// used with MOVEFILE_COPY_ALLOWED.Windows Server 2003 and Windows XP: For information about special situations where this functionality can fail,
/// and a suggested workaround solution, see Files are not exchanged when Windows Server 2003 restarts if you use the MoveFileEx function to schedule
/// a replacement for some files in the Help and Support Knowledge Base.
///
MOVEFILE_DELAY_UNTIL_REBOOT = 0x00000004,
///
/// The function does not return until the file is actually moved on the disk.Setting this value guarantees that a move performed as a copy and
/// delete operation is flushed to disk before the function returns. The flush occurs at the end of the copy operation.This value has no effect if
/// MOVEFILE_DELAY_UNTIL_REBOOT is set.
///
MOVEFILE_WRITE_THROUGH = 0x00000008,
/// Reserved for future use.
MOVEFILE_CREATE_HARDLINK = 0x00000010,
///
/// The function fails if the source file is a link source, but the file cannot be tracked after the move. This situation can occur if the
/// destination is a volume formatted with the FAT file system.
///
MOVEFILE_FAIL_IF_NOT_TRACKABLE = 0x00000020
}
/// ReplaceFile options.
public enum REPLACEFILE
{
/// This value is not supported.
REPLACEFILE_WRITE_THROUGH = 0x00000001,
///
/// Ignores errors that occur while merging information (such as attributes and ACLs) from the replaced file to the replacement file. Therefore, if
/// you specify this flag and do not have WRITE_DAC access, the function succeeds but the ACLs are not preserved.
///
REPLACEFILE_IGNORE_MERGE_ERRORS = 0x00000002,
///
/// Ignores errors that occur while merging ACL information from the replaced file to the replacement file. Therefore, if you specify this flag and
/// do not have WRITE_DAC access, the function succeeds but the ACLs are not preserved. To compile an application that uses this value, define the
/// _WIN32_WINNT macro as 0x0600 or later.
/// Windows Server 2003 and Windows XP: This value is not supported.
///
REPLACEFILE_IGNORE_ACL_ERRORS = 0x00000004,
}
///
/// Defines values that are used with the FindFirstStreamW function to specify the information level of the returned data.
///
// typedef enum _STREAM_INFO_LEVELS { FindStreamInfoStandard = 0, FindStreamInfoMaxInfoLevel = 1} STREAM_INFO_LEVELS;
[PInvokeData("WinBase.h", MSDNShortId = "aa365675")]
public enum STREAM_INFO_LEVELS
{
///
/// The FindFirstStreamW function retrieves standard stream information. The data is returned in a WIN32_FIND_STREAM_DATA structure.
///
FindStreamInfoStandard,
}
/// Flags used in the function.
[PInvokeData("WinBase.h")]
public enum SymbolicLinkType : uint
{
/// The link target is a file.
SYMBOLIC_LINK_FLAG_FILE = 0x0,
/// The link target is a directory.
SYMBOLIC_LINK_FLAG_DIRECTORY = 0x1
}
///
///
/// Determines whether the file I/O functions are using the ANSI or OEM character set code page. This function is useful for 8-bit console input and
/// output operations.
///
///
///
/// If the set of file I/O functions is using the ANSI code page, the return value is nonzero.
/// If the set of file I/O functions is using the OEM code page, the return value is zero.
///
// BOOL WINAPI AreFileApisANSI(void);
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa363781")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool AreFileApisANSI();
/// Determines whether the specified name can be used to create a file on a FAT file system.
/// The file name, in 8.3 format.
/// A pointer to a buffer that receives the OEM string that corresponds to Name. This parameter can be NULL.
/// The size of the lpOemName buffer, in characters. If lpOemName is NULL, this parameter must be 0 (zero).
///
/// Indicates whether or not a name contains spaces. This parameter can be NULL. If the name is not a valid 8.3 FAT file system name, this
/// parameter is undefined.
///
///
/// If the function succeeds, this parameter indicates whether a file name is a valid 8.3 FAT file name when the current OEM code page is applied to the
/// file name.
///
///
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is 0 (zero). To get extended error information, call GetLastError.
///
// BOOL WINAPI CheckNameLegalDOS8Dot3( _In_ LPCTSTR lpName, _Out_opt_ LPSTR lpOemName, _In_ DWORD OemNameSize, _Out_opt_ PBOOL pbNameContainsSpaces,
// _Out_ PBOOL pbNameLegal); https://msdn.microsoft.com/en-us/library/windows/desktop/aa363807(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("WinBase.h", MSDNShortId = "aa363807")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CheckNameLegalDOS8Dot3([In] string lpName, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder lpOemName, uint OemNameSize, [Out, MarshalAs(UnmanagedType.Bool)] out bool pbNameContainsSpaces, [Out, MarshalAs(UnmanagedType.Bool)] out bool pbNameLegal);
///
/// Copies an existing file to a new file.
///
/// The CopyFileEx function provides two additional capabilities. CopyFileEx can call a specified callback function each time a portion of
/// the copy operation is completed, and CopyFileEx can be canceled during the copy operation.
///
/// To perform this operation as a transacted operation, use the CopyFileTransacted function.
///
///
/// The name of an existing file.
///
/// 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 lpExistingFileName does not exist, CopyFile fails, and GetLastError returns ERROR_FILE_NOT_FOUND.
///
///
/// The name of the new file.
///
/// 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 this parameter is TRUE and the new file specified by lpNewFileName already exists, the function fails. If this parameter is FALSE
/// and the new file already exists, the function overwrites the existing file and succeeds.
///
///
/// 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 CopyFile( _In_ LPCTSTR lpExistingFileName, _In_ LPCTSTR lpNewFileName, _In_ BOOL bFailIfExists); https://msdn.microsoft.com/en-us/library/windows/desktop/aa363851(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("WinBase.h", MSDNShortId = "aa363851")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CopyFile([In] string lpExistingFileName, [In] string lpNewFileName, [MarshalAs(UnmanagedType.Bool)] bool bFailIfExists);
///
/// Copies an existing file to a new file, notifying the application of its progress through a callback function.
/// To perform this operation as a transacted operation, use the CopyFileTransacted function.
///
///
/// The name of an existing file.
///
/// 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 lpExistingFileName does not exist, the CopyFileEx function fails, and the GetLastError function returns ERROR_FILE_NOT_FOUND.
///
///
/// The name of the new file.
///
/// 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.
///
///
///
/// The address of a callback function of type LPPROGRESS_ROUTINE that is called each time another portion of the file has been copied. This
/// parameter can be NULL. For more information on the progress callback function, see the CopyProgressRoutine function.
///
/// The argument to be passed to the callback function. This parameter can be NULL.
///
/// If this flag is set to TRUE during the copy operation, the operation is canceled. Otherwise, the copy operation will continue to completion.
///
///
/// Flags that specify how the file is to be copied. This parameter can be a combination of the following values.
///
///
///
/// Value
/// Meaning
///
/// -
/// COPY_FILE_ALLOW_DECRYPTED_DESTINATION0x00000008
/// An attempt to copy an encrypted file will succeed even if the destination copy cannot be encrypted.
///
/// -
/// COPY_FILE_COPY_SYMLINK0x00000800
///
/// If the source file is a symbolic link, the destination file is also a symbolic link pointing to the same file that the source symbolic link is
/// pointing to. Windows Server 2003 and Windows XP: This value is not supported.
///
///
/// -
/// COPY_FILE_FAIL_IF_EXISTS0x00000001
/// The copy operation fails immediately if the target file already exists.
///
/// -
/// COPY_FILE_NO_BUFFERING0x00001000
///
/// The copy operation is performed using unbuffered I/O, bypassing system I/O cache resources. Recommended for very large file transfers. Windows Server
/// 2003 and Windows XP: This value is not supported.
///
///
/// -
/// COPY_FILE_OPEN_SOURCE_FOR_WRITE0x00000004
/// The file is copied and the original file is opened for write access.
///
/// -
/// COPY_FILE_RESTARTABLE0x00000002
///
/// Progress of the copy is tracked in the target file in case the copy fails. The failed copy can be restarted at a later time by specifying the same
/// values for lpExistingFileName and lpNewFileName as those used in the call that failed. This can significantly slow down the copy operation as the new
/// file may be flushed multiple times during the copy operation.
///
///
///
///
///
///
/// 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 lpProgressRoutine returns PROGRESS_CANCEL due to the user canceling the operation, CopyFileEx will return zero and
/// GetLastError will return ERROR_REQUEST_ABORTED. In this case, the partially copied destination file is deleted.
///
///
/// If lpProgressRoutine returns PROGRESS_STOP due to the user stopping the operation, CopyFileEx will return zero and GetLastError
/// will return ERROR_REQUEST_ABORTED. In this case, the partially copied destination file is left intact.
///
///
// BOOL WINAPI CopyFileEx( _In_ LPCTSTR lpExistingFileName, _In_ LPCTSTR lpNewFileName, _In_opt_ LPPROGRESS_ROUTINE lpProgressRoutine, _In_opt_ LPVOID
// lpData, _In_opt_ LPBOOL pbCancel, _In_ DWORD dwCopyFlags); https://msdn.microsoft.com/en-us/library/windows/desktop/aa363852(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("WinBase.h", MSDNShortId = "aa363852")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CopyFileEx([In] string lpExistingFileName, [In] string lpNewFileName, CopyProgressRoutine lpProgressRoutine, [In] IntPtr lpData, [In] IntPtr pbCancel, COPY_FILE dwCopyFlags);
///
///
/// Creates a new directory with the attributes of a specified template directory. If the underlying file system supports security on files and
/// directories, the function applies a specified security descriptor to the new directory. The new directory retains the other attributes of the
/// specified template directory.
///
/// To perform this operation as a transacted operation, use the CreateDirectoryTransacted function.
///
///
/// The path of the directory to use as a template when creating the new 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.
///
///
///
/// The path of the directory to be created.
///
/// 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.
///
///
///
///
/// 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 access control lists (ACL) in the default security
/// descriptor for a directory are inherited from its parent directory.
///
///
/// The target file system must support security on files and directories for this parameter to have an effect. This is indicated when
/// GetVolumeInformation returns FS_PERSISTENT_ACLS.
///
///
///
/// 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. Possible errors include the following.
///
///
///
///
/// Return code
/// Description
///
/// -
/// ERROR_ALREADY_EXISTS
/// The specified directory already exists.
///
/// -
/// ERROR_PATH_NOT_FOUND
///
/// One or more intermediate directories do not exist. This function only creates the final directory in the path. To create all intermediate directories
/// on the path, use the SHCreateDirectoryEx function.
///
///
///
///
///
// BOOL WINAPI CreateDirectoryEx( _In_ LPCTSTR lpTemplateDirectory, _In_ LPCTSTR lpNewDirectory, _In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes); https://msdn.microsoft.com/en-us/library/windows/desktop/aa363856(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("WinBase.h", MSDNShortId = "aa363856")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CreateDirectoryEx([In] string lpTemplateDirectory, [In] string lpNewDirectory, [In] SECURITY_ATTRIBUTES lpSecurityAttributes);
///
/// Establishes a hard link between an existing file and a new file. This function is only supported on the NTFS file system, and only for files, not directories.
///
///
/// The name of the new file.
/// This parameter may include the path but cannot specify the name of a 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.
///
/// Tip Starting with Windows 10, version 1607, for the Unicode version of this function ( CreateHardLinkW), 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 name of the existing file.
/// This parameter may include the path but cannot specify the name of a 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.
///
/// Tip Starting with Windows 10, version 1607, for the Unicode version of this function ( CreateHardLinkW), 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.
///
/// Reserved; must be NULL.
///
[DllImport(Lib.Kernel32, CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
[PInvokeData("WinBase.h", MSDNShortId = "aa363860")]
public static extern bool CreateHardLink(string lpFileName, string lpExistingFileName, [Optional] IntPtr lpSecurityAttributes);
/// Creates a symbolic link.
///
/// The symbolic link to be created.
///
/// This parameter may include the path. 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.
///
/// Tip Starting with Windows 10, version 1607, for the Unicode version of this function ( CreateSymbolicLinkW), 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 name of the target for the symbolic link to be created.
///
/// If lpTargetFileName has a device name associated with it, the link is treated as an absolute link; otherwise, the link is treated as a relative link.
///
///
/// This parameter may include the path. 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.
///
/// Tip Starting with Windows 10, version 1607, for the Unicode version of this function ( CreateSymbolicLinkW), 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.
///
/// Indicates whether the link target, lpTargetFileName, is a directory.
///
/// f 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, CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
[PInvokeData("WinBase.h", MSDNShortId = "aa363866")]
public static extern bool CreateSymbolicLink(string lpSymlinkFileName, string lpTargetFileName, SymbolicLinkType dwFlags);
/// Creates an enumeration of all the hard links to the specified file.
/// The name of the file.
/// An enumeration of all the hard links to the specified file.
public static IEnumerable EnumFileLinks(string fileName) => EnumFindMethods((sb, sz) => FindFirstFileName(fileName, 0, ref sz, sb), (h, sb, sz) => FindNextFileName(h, ref sz, sb));
/// Enumerates the streams in the specified file or directory.
/// The fully qualified file name.
/// The streams in the specified file or directory.
public static IEnumerable EnumFileStreams(string fileName)
{
var ptr = SafeCoTaskMemHandle.CreateFromStructure();
var h = FindFirstStream(fileName, STREAM_INFO_LEVELS.FindStreamInfoStandard, (IntPtr)ptr);
if (h.IsInvalid)
{
var err = Win32Error.GetLastError();
if (err == Win32Error.ERROR_HANDLE_EOF)
yield break;
else
err.ThrowIfFailed();
}
while (!h.IsInvalid)
{
yield return ptr.ToStructure();
if (!FindNextStream(h, (IntPtr)ptr))
{
var err = Win32Error.GetLastError();
if (err != Win32Error.ERROR_HANDLE_EOF)
err.ThrowIfFailed();
}
}
}
/// Retrieves the names of all mounted folders on the specified volume.
/// A volume GUID path for the volume to scan for mounted folders. A trailing backslash is required.
/// The names of the mounted folders that are found.
public static IEnumerable EnumVolumeMountPoints(string volumeGuidPath) => EnumFindMethods((sb, sz) => FindFirstVolumeMountPoint(volumeGuidPath, sb, sz), (h, sb, sz) => FindNextVolumeMountPoint(h, sb, sz));
///
///
/// Creates an enumeration of all the hard links to the specified file. The FindFirstFileNameW function returns a handle to the enumeration that
/// can be used on subsequent calls to the FindNextFileNameW function.
///
/// To perform this operation as a transacted operation, use the FindFirstFileNameTransactedW function.
///
///
/// The name of the file.
///
///
/// Reserved; specify zero (0).
///
///
///
/// The size of the buffer pointed to by the LinkName parameter, in characters. If this call fails and the error returned from the GetLastError
/// function is ERROR_MORE_DATA (234), the value that is returned by this parameter is the size that the buffer pointed to by LinkName must be to
/// contain all the data.
///
///
///
/// A pointer to a buffer to store the first link name found for lpFileName.
///
///
///
/// If the function succeeds, the return value is a search handle that can be used with the FindNextFileNameW function or closed with the
/// FindClose function.
///
///
/// If the function fails, the return value is INVALID_HANDLE_VALUE (0xffffffff). To get extended error information, call the GetLastError function.
///
///
// HANDLE WINAPI FindFirstFileNameW( _In_ LPCWSTR lpFileName, _In_ DWORD dwFlags, _Inout_ LPDWORD StringLength, _Inout_ PWCHAR LinkName);
[DllImport(Lib.Kernel32, SetLastError = true, EntryPoint = "FindFirstFileNameW", CharSet = CharSet.Unicode)]
[PInvokeData("WinBase.h", MSDNShortId = "aa364421")]
public static extern SafeSearchHandle FindFirstFileName(string lpFileName, uint dwFlags, ref uint StringLength, StringBuilder LinkName);
///
/// Enumerates the first stream with a ::$DATA stream type in the specified file or directory.
/// To perform this operation as a transacted operation, use the FindFirstStreamTransactedW function.
///
/// The fully qualified file name.
///
/// The information level of the returned data. This parameter is one of the values in the STREAM_INFO_LEVELS enumeration type.
///
///
///
/// Value
/// Meaning
///
/// -
/// FindStreamInfoStandard = 0
/// The data is returned in a WIN32_FIND_STREAM_DATA structure.
///
///
///
///
///
/// A pointer to a buffer that receives the file stream data. The format of this data depends on the value of the InfoLevel parameter.
///
/// Reserved for future use. This parameter must be zero.
///
/// If the function succeeds, the return value is a search handle that can be used in subsequent calls to the FindNextStreamW function.
/// If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call GetLastError.
/// If no streams can be found, the function fails and GetLastError returns ERROR_HANDLE_EOF (38).
///
// HANDLE WINAPI FindFirstStreamW( _In_ LPCWSTR lpFileName, _In_ STREAM_INFO_LEVELS InfoLevel, _Out_ LPVOID lpFindStreamData, _Reserved_ DWORD dwFlags); https://msdn.microsoft.com/en-us/library/windows/desktop/aa364424(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, EntryPoint = "FindFirstStreamW", CharSet = CharSet.Unicode)]
[PInvokeData("WinBase.h", MSDNShortId = "aa364424")]
public static extern SafeSearchHandle FindFirstStream(string lpFileName, STREAM_INFO_LEVELS InfoLevel, [Out] IntPtr lpFindStreamData, [Optional] uint dwFlags);
///
/// Retrieves the name of a mounted folder on the specified volume. FindFirstVolumeMountPoint is used to begin scanning the mounted folders on a volume.
///
/// A volume GUID path for the volume to scan for mounted folders. A trailing backslash is required.
/// A pointer to a buffer that receives the name of the first mounted folder that is found.
/// The length of the buffer that receives the path to the mounted folder, in TCHAR s.
///
///
/// If the function succeeds, the return value is a search handle used in a subsequent call to the FindNextVolumeMountPoint and
/// FindVolumeMountPointClose functions.
///
///
/// If the function fails to find a mounted folder on the volume, the return value is the INVALID_HANDLE_VALUE error code. To get extended error
/// information, call GetLastError.
///
///
// HANDLE WINAPI FindFirstVolumeMountPoint( _In_ LPTSTR lpszRootPathName, _Out_ LPTSTR lpszVolumeMountPoint, _In_ DWORD cchBufferLength); https://msdn.microsoft.com/en-us/library/windows/desktop/aa364426(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("WinBase.h", MSDNShortId = "aa364426")]
public static extern SafeVolumeMountPointHandle FindFirstVolumeMountPoint([In] string lpszRootPathName, [Out] StringBuilder lpszVolumeMountPoint, uint cchBufferLength);
///
/// Continues enumerating the hard links to a file using the handle returned by a successful call to the FindFirstFileNameW function.
///
///
/// A handle to the enumeration that is returned by a successful call to FindFirstFileNameW.
///
///
///
/// The size of the LinkName parameter, in characters. If this call fails and the error is ERROR_MORE_DATA, the value that is returned by this
/// parameter is the size that LinkName must be to contain all the data.
///
///
///
/// A pointer to a buffer to store the first link name found for lpFileName.
///
///
/// 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.
/// If no matching files can be found, the GetLastError function returns ERROR_HANDLE_EOF.
///
// BOOL WINAPI FindNextFileNameW( _In_ HANDLE hFindStream, _Inout_ LPDWORD StringLength, _Inout_ PWCHAR LinkName);
[DllImport(Lib.Kernel32, SetLastError = true, EntryPoint = "FindNextFileNameW", CharSet = CharSet.Unicode)]
[PInvokeData("WinBase.h", MSDNShortId = "aa364429")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool FindNextFileName(SafeSearchHandle hFindStream, ref uint StringLength, StringBuilder LinkName);
///
/// Continues a stream search started by a previous call to the FindFirstStreamW function.
///
///
/// The search handle returned by a previous call to the FindFirstStreamW function.
///
///
/// A pointer to the WIN32_FIND_STREAM_DATA structure that receives information about the stream.
///
///
/// 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 more streams can be found,
/// GetLastError returns ERROR_HANDLE_EOF (38).
///
///
// BOOL WINAPI FindNextStreamW( _In_ HANDLE hFindStream, _Out_ LPVOID lpFindStreamData);
[DllImport(Lib.Kernel32, SetLastError = true, EntryPoint = "FindNextStreamW", CharSet = CharSet.Unicode)]
[PInvokeData("WinBase.h", MSDNShortId = "aa364430")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool FindNextStream([In] SafeSearchHandle hFindStream, [Out] IntPtr lpFindStreamData);
///
/// Continues a mounted folder search started by a call to the FindFirstVolumeMountPoint function. FindNextVolumeMountPoint finds one
/// mounted folder per call.
///
/// A mounted folder search handle returned by a previous call to the FindFirstVolumeMountPoint function.
/// A pointer to a buffer that receives the name of the mounted folder that is found.
/// The length of the buffer that receives the mounted folder name, 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 more mounted folders can be
/// found, the GetLastError function returns the ERROR_NO_MORE_FILES error code. In that case, close the search with the
/// FindVolumeMountPointClose function.
///
///
// BOOL WINAPI FindNextVolumeMountPoint( _In_ HANDLE hFindVolumeMountPoint, _Out_ LPTSTR lpszVolumeMountPoint, _In_ DWORD cchBufferLength); https://msdn.microsoft.com/en-us/library/windows/desktop/aa364432(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("WinBase.h", MSDNShortId = "aa364432")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool FindNextVolumeMountPoint([In] SafeVolumeMountPointHandle hFindVolumeMountPoint, [Out] StringBuilder lpszVolumeMountPoint, uint cchBufferLength);
///
/// Closes the specified mounted folder search handle. The FindFirstVolumeMountPoint and FindNextVolumeMountPoint functions use this search
/// handle to locate mounted folders on a specified volume.
///
///
/// The mounted folder search handle to be closed. This handle must have been previously opened by the FindFirstVolumeMountPoint 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 FindVolumeMountPointClose( _In_ HANDLE hFindVolumeMountPoint); https://msdn.microsoft.com/en-us/library/windows/desktop/aa364435(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa364435")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool FindVolumeMountPointClose([In] IntPtr hFindVolumeMountPoint);
///
/// Retrieves the actual number of bytes of disk storage used to store a specified file. If the file is located on a volume that supports compression and
/// the file is compressed, the value obtained is the compressed size of the specified file. If the file is located on a volume that supports sparse
/// files and the file is a sparse file, the value obtained is the sparse size of the specified file.
///
///
/// The name of the file.
/// Do not specify the name of a file on a nonseeking device, such as a pipe or a communications device, as its file size has no meaning.
///
/// This parameter may include the path. In the ANSI version of this function, the name is limited to 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.
///
///
/// Tip Starting with Windows 10, version 1607, for the Unicode version of this function ( GetCompressedFileSizeW), you can opt-in to
/// remove the limitation without prepending "\\?\". See the "Maximum Path Length Limitation" section of
/// Naming Files, Paths, and Namespaces for details.
///
///
///
/// The high-order DWORD of the compressed file size. The function's return value is the low-order DWORD of the compressed file size.
///
/// This parameter can be NULL if the high-order DWORD of the compressed file size is not needed.Files less than 4 gigabytes in size do not need the
/// high-order DWORD.
///
///
///
/// If the function succeeds, the return value is the low-order DWORD of the actual number of bytes of disk storage used to store the specified file, and
/// if is non-NULL, the function puts the high-order DWORD of that actual value into the DWORD pointed to by that
/// parameter. This is the compressed file size for compressed files, the actual file size for noncompressed files.
///
/// If the function fails, and is NULL, the return value is INVALID_FILE_SIZE. To get extended error information, call GetLastError.
///
///
/// If the return value is INVALID_FILE_SIZE and is non-NULL, an application must call GetLastError to determine
/// whether the function has succeeded (value is NO_ERROR) or failed (value is other than NO_ERROR).
///
///
///
/// An application can determine whether a volume is compressed by calling
/// , then checking the status of the
/// FS_VOL_IS_COMPRESSED flag in the DWORD value pointed to by that function's lpFileSystemFlags parameter.
///
/// If the file is not located on a volume that supports compression or sparse files, or if the file is not compressed or a sparse file, the value
/// obtained is the actual file size, the same as the value returned by a call to GetFileSize.
///
/// Symbolic link behavior—If the path points to a symbolic link, the function returns the file size of the target.
///
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("WinBase.h", MSDNShortId = "aa364930")]
public static extern uint GetCompressedFileSize(string lpFileName, ref uint lpFileSizeHigh);
///
/// Moves an existing file or a directory, including its children.
/// To specify how to move the file, use the MoveFileEx or MoveFileWithProgress function.
/// To perform this operation as a transacted operation, use the MoveFileTransacted function.
///
///
/// The current name of the file or directory on the local computer.
///
/// 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.
///
///
///
///
/// The new name for the file or directory. The new name must not already exist. A new file may be on a different file system or drive. A new directory
/// must be on the same drive.
///
///
/// 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 MoveFile( _In_ LPCTSTR lpExistingFileName, _In_ LPCTSTR lpNewFileName); https://msdn.microsoft.com/en-us/library/windows/desktop/aa365239(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("WinBase.h", MSDNShortId = "aa365239")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool MoveFile([In] string lpExistingFileName, [In] string lpNewFileName);
///
/// Moves an existing file or directory, including its children, with various move options.
///
/// The MoveFileWithProgress function is equivalent to the MoveFileEx function, except that MoveFileWithProgress allows you to
/// provide a callback function that receives progress notifications.
///
/// To perform this operation as a transacted operation, use the MoveFileTransacted function.
///
///
/// The current name of the file or directory on the local computer.
///
/// If dwFlags specifies MOVEFILE_DELAY_UNTIL_REBOOT, the file cannot exist on a remote share, because delayed operations are performed before the
/// network is available.
///
///
/// 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
///
///
///
/// The new name of the file or directory on the local computer.
///
/// When moving a file, the destination can be on a different file system or volume. If the destination is on another drive, you must set the
/// MOVEFILE_COPY_ALLOWED flag in dwFlags.
///
/// When moving a directory, the destination must be on the same drive.
///
/// If dwFlags specifies MOVEFILE_DELAY_UNTIL_REBOOT and lpNewFileName is NULL, MoveFileEx registers the lpExistingFileName file to
/// be deleted when the system restarts. If lpExistingFileName refers to a directory, the system removes the directory at restart only if the directory
/// is empty.
///
///
/// 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
///
///
///
/// This parameter can be one or more of the following values.
///
///
///
/// Value
/// Meaning
///
/// -
/// MOVEFILE_COPY_ALLOWED2 (0x2)
///
/// If the file is to be moved to a different volume, the function simulates the move by using the CopyFile and DeleteFile functions.If the file is
/// successfully copied to a different volume and the original file is unable to be deleted, the function succeeds leaving the source file intact.This
/// value cannot be used with MOVEFILE_DELAY_UNTIL_REBOOT.
///
///
/// -
/// MOVEFILE_CREATE_HARDLINK16 (0x10)
/// Reserved for future use.
///
/// -
/// MOVEFILE_DELAY_UNTIL_REBOOT4 (0x4)
///
/// The system does not move the file until the operating system is restarted. The system moves the file immediately after AUTOCHK is executed, but
/// before creating any paging files. Consequently, this parameter enables the function to delete paging files from previous startups.This value can be
/// used only if the process is in the context of a user who belongs to the administrators group or the LocalSystem account. This value cannot be used
/// with MOVEFILE_COPY_ALLOWED.Windows Server 2003 and Windows XP: For information about special situations where this functionality can fail, and a
/// suggested workaround solution, see Files are not exchanged when Windows Server 2003 restarts if you use the MoveFileEx function to schedule a
/// replacement for some files in the Help and Support Knowledge Base.
///
///
/// -
/// MOVEFILE_FAIL_IF_NOT_TRACKABLE32 (0x20)
///
/// The function fails if the source file is a link source, but the file cannot be tracked after the move. This situation can occur if the destination is
/// a volume formatted with the FAT file system.
///
///
/// -
/// MOVEFILE_REPLACE_EXISTING1 (0x1)
///
/// If a file named lpNewFileName exists, the function replaces its contents with the contents of the lpExistingFileName file, provided that security
/// requirements regarding access control lists (ACLs) are met. For more information, see the Remarks section of this topic.This value cannot be used if
/// lpNewFileName or lpExistingFileName names a directory.
///
///
/// -
/// MOVEFILE_WRITE_THROUGH8 (0x8)
///
/// The function does not return until the file is actually moved on the disk.Setting this value guarantees that a move performed as a copy and delete
/// operation is flushed to disk before the function returns. The flush occurs at the end of the copy operation.This value has no effect if
/// MOVEFILE_DELAY_UNTIL_REBOOT is set.
///
///
///
///
///
///
/// 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 MoveFileEx( _In_ LPCTSTR lpExistingFileName, _In_opt_ LPCTSTR lpNewFileName, _In_ DWORD dwFlags); https://msdn.microsoft.com/en-us/library/windows/desktop/aa365240(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("WinBase.h", MSDNShortId = "aa365240")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool MoveFileEx([In] string lpExistingFileName, [In] string lpNewFileName, MOVEFILE dwFlags);
///
/// Moves a file or directory, including its children. You can provide a callback function that receives progress notifications.
/// To perform this operation as a transacted operation, use the MoveFileTransacted function.
///
///
/// The name of the existing file or directory on the local computer.
///
/// If dwFlags specifies MOVEFILE_DELAY_UNTIL_REBOOT, the file cannot exist on a remote share because delayed operations are performed before the
/// network is available.
///
///
/// 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.
///
///
///
/// The new name of the file or directory on the local computer.
///
/// When moving a file, lpNewFileName can be on a different file system or volume. If lpNewFileName is on another drive, you must set the
/// MOVEFILE_COPY_ALLOWED flag in dwFlags.
///
/// When moving a directory, lpExistingFileName and lpNewFileName must be on the same drive.
///
/// If dwFlags specifies MOVEFILE_DELAY_UNTIL_REBOOT and lpNewFileName is NULL, MoveFileWithProgress registers lpExistingFileName to
/// be deleted when the system restarts. The function fails if it cannot access the registry to store the information about the delete operation. If
/// lpExistingFileName refers to a directory, the system removes the directory at restart only if the directory is empty.
///
///
/// 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.
///
///
///
/// A pointer to a CopyProgressRoutine callback function that is called each time another portion of the file has been moved. The callback
/// function can be useful if you provide a user interface that displays the progress of the operation. This parameter can be NULL.
///
/// An argument to be passed to the CopyProgressRoutine callback function. This parameter can be NULL.
///
/// The move options. This parameter can be one or more of the following values.
///
///
///
/// Value
/// Meaning
///
/// -
/// MOVEFILE_COPY_ALLOWED2 (0x2)
///
/// If the file is to be moved to a different volume, the function simulates the move by using the CopyFile and DeleteFile functions.If the file is
/// successfully copied to a different volume and the original file is unable to be deleted, the function succeeds leaving the source file intact.This
/// value cannot be used with MOVEFILE_DELAY_UNTIL_REBOOT.
///
///
/// -
/// MOVEFILE_CREATE_HARDLINK16 (0x10)
/// Reserved for future use.
///
/// -
/// MOVEFILE_DELAY_UNTIL_REBOOT4 (0x4)
///
/// The system does not move the file until the operating system is restarted. The system moves the file immediately after AUTOCHK is executed, but
/// before creating any paging files. Consequently, this parameter enables the function to delete paging files from previous startups.This value can only
/// be used if the process is in the context of a user who belongs to the administrators group or the LocalSystem account.This value cannot be used with MOVEFILE_COPY_ALLOWED.
///
///
/// -
/// MOVEFILE_FAIL_IF_NOT_TRACKABLE32 (0x20)
///
/// The function fails if the source file is a link source, but the file cannot be tracked after the move. This situation can occur if the destination is
/// a volume formatted with the FAT file system.
///
///
/// -
/// MOVEFILE_REPLACE_EXISTING1 (0x1)
///
/// If a file named lpNewFileName exists, the function replaces its contents with the contents of the lpExistingFileName file.This value cannot be used
/// if lpNewFileName or lpExistingFileName names a directory.
///
///
/// -
/// MOVEFILE_WRITE_THROUGH8 (0x8)
///
/// The function does not return until the file has actually been moved on the disk.Setting this value guarantees that a move performed as a copy and
/// delete operation is flushed to disk before the function returns. The flush occurs at the end of the copy operation.This value has no effect if
/// MOVEFILE_DELAY_UNTIL_REBOOT is set.
///
///
///
///
///
///
/// 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.
///
/// When moving a file across volumes, if lpProgressRoutine returns PROGRESS_CANCEL due to the user canceling the operation,
/// MoveFileWithProgress will return zero and GetLastError will return ERROR_REQUEST_ABORTED. The existing file is left intact.
///
///
/// When moving a file across volumes, if lpProgressRoutine returns PROGRESS_STOP due to the user stopping the operation,
/// MoveFileWithProgress will return zero and GetLastError will return ERROR_REQUEST_ABORTED. The existing file is left intact.
///
///
// BOOL WINAPI MoveFileWithProgress( _In_ LPCTSTR lpExistingFileName, _In_opt_ LPCTSTR lpNewFileName, _In_opt_ LPPROGRESS_ROUTINE lpProgressRoutine,
// _In_opt_ LPVOID lpData, _In_ DWORD dwFlags); https://msdn.microsoft.com/en-us/library/windows/desktop/aa365242(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("WinBase.h", MSDNShortId = "aa365242")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool MoveFileWithProgress([In] string lpExistingFileName, [In] string lpNewFileName, CopyProgressRoutine lpProgressRoutine, [In] IntPtr lpData, MOVEFILE dwFlags);
/// Creates, opens, reopens, or deletes a file.
///
/// The name of the file.
///
/// The string must consist of characters from the 8-bit Windows character set. The OpenFile function does not support Unicode file names or
/// opening named pipes.
///
///
///
/// A pointer to the OFSTRUCT structure that receives information about a file when it is first opened.
/// The structure can be used in subsequent calls to the OpenFile function to see an open file.
///
/// The OFSTRUCT structure contains a path string member with a length that is limited to OFS_MAXPATHNAME characters, which is 128
/// characters. Because of this, you cannot use the OpenFile function to open a file with a path length that exceeds 128 characters. The
/// CreateFile function does not have this path length limitation.
///
///
///
/// The action to be taken.
/// This parameter can be one or more of the following values.
///
///
///
/// Value
/// Meaning
///
/// -
/// OF_CANCEL0x00000800
/// Ignored.To produce a dialog box containing a Cancel button, use OF_PROMPT.
///
/// -
/// OF_CREATE0x00001000
/// Creates a new file.If the file exists, it is truncated to zero (0) length.
///
/// -
/// OF_DELETE0x00000200
/// Deletes a file.
///
/// -
/// OF_EXIST0x00004000
/// Opens a file and then closes it.Use this to test for the existence of a file.
///
/// -
/// OF_PARSE0x00000100
/// Fills the OFSTRUCT structure, but does not do anything else.
///
/// -
/// OF_PROMPT0x00002000
///
/// Displays a dialog box if a requested file does not exist.A dialog box informs a user that the system cannot find a file, and it contains Retry and
/// Cancel buttons. The Cancel button directs OpenFile to return a file-not-found error message.
///
///
/// -
/// OF_READ0x00000000
/// Opens a file for reading only.
///
/// -
/// OF_READWRITE0x00000002
/// Opens a file with read/write permissions.
///
/// -
/// OF_REOPEN0x00008000
/// Opens a file by using information in the reopen buffer.
///
/// -
/// OF_SHARE_COMPAT0x00000000
///
/// For MS-DOS–based file systems, opens a file with compatibility mode, allows any process on a specified computer to open the file any number of
/// times.Other efforts to open a file with other sharing modes fail. This flag is mapped to the FILE_SHARE_READ|FILE_SHARE_WRITE flags of the CreateFile function.
///
///
/// -
/// OF_SHARE_DENY_NONE0x00000040
///
/// Opens a file without denying read or write access to other processes.On MS-DOS-based file systems, if the file has been opened in compatibility mode
/// by any other process, the function fails.This flag is mapped to the FILE_SHARE_READ|FILE_SHARE_WRITE flags of the CreateFile function.
///
///
/// -
/// OF_SHARE_DENY_READ0x00000030
///
/// Opens a file and denies read access to other processes.On MS-DOS-based file systems, if the file has been opened in compatibility mode, or for read
/// access by any other process, the function fails.This flag is mapped to the FILE_SHARE_WRITE flag of the CreateFile function.
///
///
/// -
/// OF_SHARE_DENY_WRITE0x00000020
///
/// Opens a file and denies write access to other processes.On MS-DOS-based file systems, if a file has been opened in compatibility mode, or for write
/// access by any other process, the function fails.This flag is mapped to the FILE_SHARE_READ flag of the CreateFile function.
///
///
/// -
/// OF_SHARE_EXCLUSIVE0x00000010
///
/// Opens a file with exclusive mode, and denies both read/write access to other processes. If a file has been opened in any other mode for read/write
/// access, even by the current process, the function fails.
///
///
/// -
/// OF_VERIFY
/// Verifies that the date and time of a file are the same as when it was opened previously.This is useful as an extra check for read-only files.
///
/// -
/// OF_WRITE0x00000001
/// Opens a file for write access only.
///
///
///
///
///
///
/// If the function succeeds, the return value specifies a file handle to use when performing file I/O. To close the file, call the CloseHandle
/// function using this handle.
///
/// If the function fails, the return value is HFILE_ERROR. To get extended error information, call GetLastError.
///
// HFILE WINAPI OpenFile( _In_ LPCSTR lpFileName, _Out_ LPOFSTRUCT lpReOpenBuff, _In_ UINT uStyle); https://msdn.microsoft.com/en-us/library/windows/desktop/aa365430(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa365430")]
public static extern SafeFileHandle OpenFile([In] [MarshalAs(UnmanagedType.LPStr)] string lpFileName, ref OFSTRUCT lpReOpenBuff, uint uStyle);
///
///
/// Retrieves information that describes the changes within the specified directory. The function does not report changes to the specified directory itself.
///
/// To track changes on a volume, see change journals.
///
///
/// A handle to the directory to be monitored. This directory must be opened with the FILE_LIST_DIRECTORY access right, or an access right such as
/// GENERIC_READ that includes the FILE_LIST_DIRECTORY access right.
///
///
/// A pointer to the DWORD-aligned formatted buffer in which the read results are to be returned. The structure of this buffer is defined by the
/// FILE_NOTIFY_INFORMATION structure. This buffer is filled either synchronously or asynchronously, depending on how the directory is opened and
/// what value is given to the lpOverlapped parameter. For more information, see the Remarks section.
///
/// The size of the buffer that is pointed to by the lpBuffer parameter, in bytes.
///
/// If this parameter is TRUE, the function monitors the directory tree rooted at the specified directory. If this parameter is FALSE, the
/// function monitors only the directory specified by the hDirectory parameter.
///
///
///
/// The filter criteria that the function checks to determine if the wait operation has completed. This parameter can be one or more of the following values.
///
///
///
///
/// Value
/// Meaning
///
/// -
/// FILE_NOTIFY_CHANGE_FILE_NAME0x00000001
///
/// 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.
///
///
/// -
/// FILE_NOTIFY_CHANGE_DIR_NAME0x00000002
///
/// 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_ATTRIBUTES0x00000004
/// Any attribute change in the watched directory or subtree causes a change notification wait operation to return.
///
/// -
/// FILE_NOTIFY_CHANGE_SIZE0x00000008
///
/// 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_LAST_WRITE0x00000010
///
/// 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_ACCESS0x00000020
/// 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_CREATION0x00000040
/// 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_SECURITY0x00000100
/// Any security-descriptor change in the watched directory or subtree causes a change notification wait operation to return.
///
///
///
///
///
/// For synchronous calls, this parameter receives the number of bytes transferred into the lpBuffer parameter. For asynchronous calls, this parameter is
/// undefined. You must use an asynchronous notification technique to retrieve the number of bytes transferred.
///
///
/// A pointer to an OVERLAPPED structure that supplies data to be used during asynchronous operation. Otherwise, this value is NULL. The
/// Offset and OffsetHigh members of this structure are not used.
///
///
/// A pointer to a completion routine to be called when the operation has been completed or canceled 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. For synchronous calls, this means that the operation succeeded. For asynchronous calls, this
/// indicates that the operation was successfully queued.
///
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
/// If the network redirector or the target file system does not support this operation, the function fails with ERROR_INVALID_FUNCTION.
///
// BOOL WINAPI ReadDirectoryChangesW( _In_ HANDLE hDirectory, _Out_ LPVOID lpBuffer, _In_ DWORD nBufferLength, _In_ BOOL bWatchSubtree, _In_ DWORD
// dwNotifyFilter, _Out_opt_ LPDWORD lpBytesReturned, _Inout_opt_ LPOVERLAPPED lpOverlapped, _In_opt_ LPOVERLAPPED_COMPLETION_ROUTINE
// lpCompletionRoutine); https://msdn.microsoft.com/en-us/library/windows/desktop/aa365465(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, EntryPoint = "ReadDirectoryChangesW", CharSet = CharSet.Unicode)]
[PInvokeData("WinBase.h", MSDNShortId = "aa365465")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern unsafe bool ReadDirectoryChanges([In] SafeFileHandle hDirectory, IntPtr lpBuffer, uint nBufferLength, [MarshalAs(UnmanagedType.Bool)] bool bWatchSubtree, FILE_NOTIFY_CHANGE dwNotifyFilter,
out uint lpBytesReturned, NativeOverlapped* lpOverlapped, FileIOCompletionRoutine lpCompletionRoutine);
///
/// Replaces one file with another file, with the option of creating a backup copy of the original file. The replacement file assumes the name of the
/// replaced file and its identity.
///
///
/// The name of the file to be replaced.
///
/// 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.
///
///
/// This file is opened with the GENERIC_READ, DELETE, and SYNCHRONIZE access rights. The sharing mode is FILE_SHARE_READ |
/// FILE_SHARE_WRITE | FILE_SHARE_DELETE.
///
/// The caller must have write access to the file to be replaced. For more information, see File Security and Access Rights.
///
///
/// The name of the file that will replace the lpReplacedFileName file.
///
/// 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.
///
///
/// The function attempts to open this file with the SYNCHRONIZE, GENERIC_READ, GENERIC_WRITE, DELETE, and WRITE_DAC
/// access rights so that it can preserve all attributes and ACLs. If this fails, the function attempts to open the file with the SYNCHRONIZE,
/// GENERIC_READ, DELETE, and WRITE_DAC access rights. No sharing mode is specified.
///
///
///
///
/// The name of the file that will serve as a backup copy of the lpReplacedFileName file. If this parameter is NULL, no backup file is created.
/// See the Remarks section for implementation details on the backup file.
///
///
/// 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.
///
///
///
/// The replacement options. This parameter can be one or more of the following values.
///
///
///
/// Value
/// Meaning
///
/// -
/// REPLACEFILE_WRITE_THROUGH0x00000001
/// This value is not supported.
///
/// -
/// REPLACEFILE_IGNORE_MERGE_ERRORS0x00000002
///
/// Ignores errors that occur while merging information (such as attributes and ACLs) from the replaced file to the replacement file. Therefore, if you
/// specify this flag and do not have WRITE_DAC access, the function succeeds but the ACLs are not preserved.
///
///
/// -
/// REPLACEFILE_IGNORE_ACL_ERRORS0x00000004
///
/// Ignores errors that occur while merging ACL information from the replaced file to the replacement file. Therefore, if you specify this flag and do
/// not have WRITE_DAC access, the function succeeds but the ACLs are not preserved. To compile an application that uses this value, define the
/// _WIN32_WINNT macro as 0x0600 or later.Windows Server 2003 and Windows XP: This value is not supported.
///
///
///
///
///
/// Reserved for future use.
/// Reserved for future use.
///
/// 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 following are possible error codes
/// for this function.
///
///
///
///
/// Return code/value
/// Description
///
/// -
/// ERROR_UNABLE_TO_MOVE_REPLACEMENT1176 (0x498)
///
/// The replacement file could not be renamed. If lpBackupFileName was specified, the replaced and replacement files retain their original file names.
/// Otherwise, the replaced file no longer exists and the replacement file exists under its original name.
///
///
/// -
/// ERROR_UNABLE_TO_MOVE_REPLACEMENT_21177 (0x499)
///
/// The replacement file could not be moved. The replacement file still exists under its original name; however, it has inherited the file streams and
/// attributes from the file it is replacing. The file to be replaced still exists with a different name. If lpBackupFileName is specified, it will be
/// the name of the replaced file.
///
///
/// -
/// ERROR_UNABLE_TO_REMOVE_REPLACED1175 (0x497)
/// The replaced file could not be deleted. The replaced and replacement files retain their original file names.
///
///
///
///
/// If any other error is returned, such as ERROR_INVALID_PARAMETER, the replaced and replacement files will retain their original file names. In
/// this scenario, a backup file does not exist and it is not guaranteed that the replacement file will have inherited all of the attributes and streams
/// of the replaced file.
///
///
// BOOL WINAPI ReplaceFile( _In_ LPCTSTR lpReplacedFileName, _In_ LPCTSTR lpReplacementFileName, _In_opt_ LPCTSTR lpBackupFileName, _In_ DWORD
// dwReplaceFlags, _Reserved_ LPVOID lpExclude, _Reserved_ LPVOID lpReserved); https://msdn.microsoft.com/en-us/library/windows/desktop/aa365512(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("WinBase.h", MSDNShortId = "aa365512")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ReplaceFile([In] string lpReplacedFileName, [In] string lpReplacementFileName, [In] string lpBackupFileName, REPLACEFILE dwReplaceFlags, [Optional] IntPtr lpExclude, [Optional] IntPtr lpReserved);
///
///
/// Causes the file I/O functions to use the ANSI character set code page for the current process. This function is useful for 8-bit console input and
/// output operations.
///
///
///
/// This function does not return a value.
///
// void WINAPI SetFileApisToANSI(void);
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa365533")]
public static extern void SetFileApisToANSI();
///
///
/// Causes the file I/O functions for the process to use the OEM character set code page. This function is useful for 8-bit console input and output operations.
///
///
///
/// This function does not return a value.
///
// void WINAPI SetFileApisToOEM(void);
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa365534")]
public static extern void SetFileApisToOEM();
///
///
/// Associates a virtual address range with the specified file handle. This indicates that the kernel should optimize any further asynchronous I/O
/// requests with overlapped structures inside this range. The overlapped range is locked in memory, and then unlocked when the file is closed. After a
/// range is associated with a file handle, it cannot be disassociated.
///
///
///
/// A handle to the file.
/// This file handle must be opened with FILE_READ_ATTRIBUTES access rights.
///
///
/// The starting address for the range.
///
///
/// The length of the range, in bytes.
///
///
/// Returns nonzero if successful or zero otherwise.
/// To get extended error information, call GetLastError.
///
// BOOL WINAPI SetFileIoOverlappedRange( _In_ HANDLE FileHandle, _In_ PUCHAR OverlappedRangeStart, _In_ ULONG Length);
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
[PInvokeData("WinBase.h", MSDNShortId = "aa365540")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetFileIoOverlappedRange([In] SafeFileHandle FileHandle, IntPtr OverlappedRangeStart, uint Length);
/// Sets the short name for the specified file. The file must be on an NTFS file system volume.
///
/// A handle to the file. The file must be opened with either the GENERIC_ALL access right or GENERIC_WRITE| DELETE, and with the
/// FILE_FLAG_BACKUP_SEMANTICS file attribute.
///
///
/// A pointer to a string that specifies the short name for the file.
///
/// Specifying an empty (zero-length) string will remove the short file name, if it exists for the file specified by the hFile parameter. If a short file
/// name does not exist, the function will do nothing and return success.
///
///
/// Windows Server 2008, Windows Vista, Windows Server 2003 and Windows XP: This behavior is not supported. The parameter must contain a valid
/// string of one or more 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. GetLastError may return one of
/// the following error codes that are specific to this function.
///
///
///
///
/// Return code
/// Description
///
/// -
/// ERROR_ALREADY_EXISTS
/// The specified short name is not unique.
///
/// -
/// ERROR_INVALID_PARAMETER
/// Either the specified file has been opened in case-sensitive mode or the specified short name is invalid.
///
///
///
///
// BOOL WINAPI SetFileShortName( _In_ HANDLE hFile, _In_ LPCTSTR lpShortName); https://msdn.microsoft.com/en-us/library/windows/desktop/aa365543(v=vs.85).aspx
[DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
[PInvokeData("WinBase.h", MSDNShortId = "aa365543")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetFileShortName([In] SafeFileHandle hFile, [In] string lpShortName);
/// Template method for using FindXX methods to get a list of strings.
/// The type of the handle returned by the method.
/// The method that gets the first value.
/// The method that gets the next value.
/// The string buffer length.
/// List of strings returned by and methods.
private static IEnumerable EnumFindMethods(Func first, Func next, uint strSz = MAX_PATH + 1) where THandle : SafeHandle
{
var sb = new StringBuilder((int)strSz, (int)strSz);
var h = first(sb, strSz);
if (h.IsInvalid)
{
var err = Win32Error.GetLastError();
if (err == Win32Error.ERROR_MORE_DATA)
{
AddCap();
h = first(sb, strSz);
if (h.IsInvalid) Win32Error.ThrowLastError();
}
else
err.ThrowIfFailed();
}
while (!h.IsInvalid)
{
yield return sb.ToString();
sb.Length = 0;
if (!next(h, sb, strSz))
{
var err = Win32Error.GetLastError();
if (err == Win32Error.ERROR_MORE_DATA)
AddCap();
else if (err != Win32Error.ERROR_NO_MORE_FILES)
err.ThrowIfFailed();
}
}
void AddCap() => sb.Capacity = strSz <= sb.Capacity ? (int)(strSz *= 2) : (int)++strSz;
}
/// Contains information about a file that the OpenFile function opened or attempted to open.
// typedef struct _OFSTRUCT { BYTE cBytes; BYTE fFixedDisk; WORD nErrCode; WORD Reserved1; WORD Reserved2; CHAR szPathName[OFS_MAXPATHNAME];} OFSTRUCT,
// *POFSTRUCT; https://msdn.microsoft.com/en-us/library/windows/desktop/aa365282(v=vs.85).aspx
[PInvokeData("WinBase.h", MSDNShortId = "aa365282")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct OFSTRUCT
{
/// The size of the structure, in bytes.
public byte cBytes;
/// If this member is nonzero, the file is on a hard (fixed) disk. Otherwise, it is not.
public byte fFixedDisk;
/// The MS-DOS error code if the OpenFile function failed.
public ushort nErrCode;
/// Reserved; do not use.
public ushort Reserved1;
/// Reserved; do not use.
public ushort Reserved2;
/// The path and file name of the file.
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string szPathName;
}
/// Contains attribute information for a file or directory. The GetFileAttributesEx function uses this structure.
[StructLayout(LayoutKind.Sequential)]
[PInvokeData("WinBase.h", MSDNShortId = "aa365739")]
public struct WIN32_FILE_ATTRIBUTE_DATA
{
/// The file system attribute information for a file or directory.
public FileFlagsAndAttributes dwFileAttributes;
/// A FILETIME structure that specifies when the file or directory is created.
public FILETIME ftCreationTime;
///
/// A FILETIME structure. For a file, the structure specifies when the file is last 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 last access time, this member is zero.
///
public FILETIME ftLastAccessTime;
///
/// A FILETIME structure. For a file, the structure specifies when the file is last written to. For a directory, the structure specifies when the
/// directory is created. If the underlying file system does not support last write time, this member is zero.
///
public FILETIME ftLastWriteTime;
/// The high-order DWORD of the file size. This member does not have a meaning for directories.
public uint nFileSizeHigh;
/// The low-order DWORD of the file size. This member does not have a meaning for directories.
public uint nFileSizeLow;
}
///
/// Contains information about the stream found by the FindFirstStreamW or FindNextStreamW function.
///
// typedef struct _WIN32_FIND_STREAM_DATA { LARGE_INTEGER StreamSize; WCHAR cStreamName[MAX_PATH + 36];} WIN32_FIND_STREAM_DATA, *PWIN32_FIND_STREAM_DATA;
[PInvokeData("WinBase.h", MSDNShortId = "aa365741")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct WIN32_FIND_STREAM_DATA
{
///
/// A LARGE_INTEGER value that specifies the size of the stream, in bytes.
///
public long StreamSize;
///
/// The name of the stream. The string name format is ":streamname:$streamtype".
///
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_PATH + 36)] private string cStreamName;
}
/// Represents a search handle used in a subsequent call to the FindNextVolumeMountPoint and retrieved by FindFirstVolumeMountPoint.
public class SafeVolumeMountPointHandle : GenericSafeHandle
{
/// Initializes a new instance of the class.
public SafeVolumeMountPointHandle() : this(IntPtr.Zero) { }
/// Initializes a new instance of the class.
/// The handle.
/// if set to true handle should be released at disposal.
public SafeVolumeMountPointHandle(IntPtr handle, bool own = true) : base(IntPtr.Zero, FindVolumeMountPointClose, true) { }
}
}
}