Type a page name and press Enter. You'll jump to the page if it exists, or you can create it if it doesn't.
To create a page in a module other than kernel32, prefix the name with the module name and a period.
CreateFile (kernel32)
.
C# Signature:
/// <summary>
/// The CreateFile function creates or opens a file, file stream, directory, physical disk, volume, console buffer, tape drive,
/// communications resource, mailslot, or named pipe. The function returns a handle that can be used to access an object.
/// </summary>
/// <param name="lpFileName"></param>
/// <param name="dwDesiredAccess"> access to the object, which can be read, write, or both</param>
/// <param name="dwShareMode">The sharing mode of an object, which can be read, write, both, or none</param>
/// <param name="SecurityAttributes">A pointer to a SECURITY_ATTRIBUTES structure that determines whether or not the returned handle can
/// be inherited by child processes. Can be null</param>
/// <param name="dwCreationDisposition">An action to take on files that exist and do not exist</param>
/// <param name="dwFlagsAndAttributes">The file attributes and flags. </param>
/// <param name="hTemplateFile">A 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</param>
/// <returns>If the function succeeds, the return value is an open handle to a specified file. If a specified file exists before the function
/// all and dwCreationDisposition is CREATE_ALWAYS or OPEN_ALWAYS, a call to GetLastError returns ERROR_ALREADY_EXISTS, even when the function
/// succeeds. If a file does not exist before the call, GetLastError returns 0 (zero).
/// If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call GetLastError.
/// </returns>
[DllImport("kernel32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
public static extern SafeFileHandle CreateFile(
string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr SecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile
);
''' <summary>
''' 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.
''' 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.
''' </summary>
''' <param name="lpFileName">The name of the file or device to be created or opened.
''' 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.
''' 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.</param>
''' <param name="dwDesiredAccess">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 and File Security and Access Rights.
''' 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.</param>
''' <param name="dwShareMode">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.
''' Note: The sharing options for each open handle remain in effect until that handle is closed, regardless of process context.</param>
''' <param name="lpSecurityAttributes">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 bInheritHandle member of the structure specifies whether the returned handle can be inherited.
''' For more information, see the Remarks section.</param>
''' <param name="dwCreationDisposition">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:</param>
''' <param name="dwFlagsAndAttributes">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 information by specifying the SECURITY_SQOS_PRESENT flag. Additional SQOS-related flags information is presented in the table following the
''' attributes and flags tables.
''' Note: 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.</param>
''' <param name="hTemplateFile">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</param>
''' <returns>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.</returns>
''' <remarks></remarks>
<System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError:=True, CharSet:=System.Runtime.InteropServices.CharSet.Auto)> _
Friend Function CreateFile(ByVal lpFileName As String, _
ByVal dwDesiredAccess As EFileAccess, _
ByVal dwShareMode As EFileShare, _
ByVal lpSecurityAttributes As IntPtr, _
ByVal dwCreationDisposition As ECreationDisposition, _
ByVal dwFlagsAndAttributes As EFileAttributes, _
ByVal hTemplateFile As IntPtr) As Microsoft.Win32.SafeHandles.SafeFileHandle
End Function
[Flags]
public enum EFileShare : uint
{
/// <summary>
///
/// </summary>
None = 0x00000000,
/// <summary>
/// Enables subsequent open operations on an object to request read access.
/// Otherwise, other processes cannot open the object if they request read access.
/// If this flag is not specified, but the object has been opened for read access, the function fails.
/// </summary>
Read = 0x00000001,
/// <summary>
/// Enables subsequent open operations on an object to request write access.
/// Otherwise, other processes cannot open the object if they request write access.
/// If this flag is not specified, but the object has been opened for write access, the function fails.
/// </summary>
Write = 0x00000002,
/// <summary>
/// Enables subsequent open operations on an object to request delete access.
/// Otherwise, other processes cannot open the object if they request delete access.
/// If this flag is not specified, but the object has been opened for delete access, the function fails.
/// </summary>
Delete = 0x00000004
}
public enum ECreationDisposition : uint
{
/// <summary>
/// Creates a new file. The function fails if a specified file exists.
/// </summary>
New = 1,
/// <summary>
/// Creates a new file, always.
/// If a file exists, the function overwrites the file, clears the existing attributes, combines the specified file attributes,
/// and flags with FILE_ATTRIBUTE_ARCHIVE, but does not set the security descriptor that the SECURITY_ATTRIBUTES structure specifies.
/// </summary>
CreateAlways = 2,
/// <summary>
/// Opens a file. The function fails if the file does not exist.
/// </summary>
OpenExisting = 3,
/// <summary>
/// Opens a file, always.
/// If a file does not exist, the function creates a file as if dwCreationDisposition is CREATE_NEW.
/// </summary>
OpenAlways = 4,
/// <summary>
/// Opens a file and truncates it so that its size is 0 (zero) bytes. The function fails if the file does not exist.
/// The calling process must open the file with the GENERIC_WRITE access right.
/// </summary>
TruncateExisting = 5
}
Friend Enum ECreationDisposition
''' <summary>
''' 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.
''' </summary>
CREATE_NEW = 1
''' <summary>
''' 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.
''' </summary>
CREATE_ALWAYS = 2
''' <summary>
''' 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.
''' </summary>
OPEN_EXISTING = 3
''' <summary>
''' 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.
''' </summary>
OPEN_ALWAYS = 4
''' <summary>
''' 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.
''' </summary>
TRUNCATE_EXISTING = 5
End Enum
Instead of the enum "EFileAttributes" supplied on this page, you can also use "System.IO.FileAttributes". The enum values are identical up to "Encrypted".
This is NOT true for "EFileAccess" and "System.IO.FileAccess"!
Notes:
None.
Tips & Tricks:
You can use the IntPtr from Createfile with FileStream. This is usefull for opening devices such as Com1:, Lpt1: and Prn.
Unlike the FileStream ctor, CreateFile also allows you to open or create Windows 2000 sub-streams (e.g. "C:\Temp.dat:SubStream1").
For example:
IntPtr ptr = CreateFile(filename,access, share,0, mode,0, IntPtr.Zero);
/* Is bad handle? INVALID_HANDLE_VALUE */
if (ptr.ToInt32() == -1)
{
/* ask the framework to marshall the win32 error code to an exception */
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
else
{
return new FileStream(ptr,access);
}
Microsoft .NET Framework 2.0 Changes
If you are using version 2.0 of the .NET framework, you will need to make a few changes because of obsolete methods in the release for OpenFile. You can no longer try the good old
Now you can use the normal .NET enums that people are familiar with
Thought I post a sample code to help out anyone else who may need help : )
/// Sample code provided as is.
/// Sample Composed by Wijaya "Wi" T
/// References:
/// http://www.dotnettalk.net/Needed_help_on_printing_from_C_and_printer-6941579-1297-a.html
/// http://www.dotnet247.com/247reference/msgs/16/84730.aspx
/// http://www.groupsrv.com/dotnet/viewtopic.php?t=72572
/// http://www.pinvoke.net/default.aspx/kernel32.CreateFile
/// Usage:
/// Initialize this class in your main code (see below),
/// and walla you are now printing!
///
/// e.g.:
/// PrintFactory objPrintFactory = new PrintFactory();
/// Thank you:
/// Thank you all who have been contributing to printing to LPT port.
/// God Bless you! : )
/// Addt'l info:
/// Don't forget to reference:
/// using System.Runtime.InteropServices;
/// using System.IO;
///
public class PrintFactory
{
public const short FILE_ATTRIBUTE_NORMAL = 0x80;
public const short INVALID_HANDLE_VALUE = -1;
public const uint GENERIC_READ = 0x80000000;
public const uint GENERIC_WRITE = 0x40000000;
public const uint CREATE_NEW = 1;
public const uint CREATE_ALWAYS = 2;
public const uint OPEN_EXISTING = 3;
/* Is bad handle? INVALID_HANDLE_VALUE */
if (ptr.ToInt32() == -1)
{
/* ask the framework to marshall the win32 error code to an exception */
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
else
{
String Temp = "This is a test print";
//This is the cut command on Star TSP 600 Printer
char[] prnCmdCut = {(char)27, (char)100, (char)51};
FileStream lpt = new FileStream(ptr,FileAccess.ReadWrite);
Byte[] Buff = new Byte[1024];
//Check to see if your printer support ASCII encoding or Unicode.
//If unicode is supported, use the following:
//Buff = System.Text.Encoding.Unicode.GetBytes(Temp);
Buff = System.Text.Encoding.ASCII.GetBytes(Temp);
lpt.Write(Buff,0,Buff.Length);
Buff = System.Text.Encoding.ASCII.GetBytes(prnCmdCut);
lpt.Write(Buff,0,Buff.Length);
lpt.Close();
}
}
}
Sample Code with C#:
This code writes to disk as a file. Tested on USB flash drives as zerofill utility.
/* Sample Code provided by MertG */
/* References: */
/* This page,
http://stackoverflow.com/questions/4288031/createfile-in-kernel32-dll-does-not-allow-me-to-open-a-physical-disk */
//Using directives needed:
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
//function to read
private static byte[] ReadDrive( string FileName, int sizeToRead ) {
if ( (sizeToRead < 1) || (sizeToRead == null) ) throw new System.ArgumentException("Size parameter cannot be null or 0 or less than 0!");
SafeFileHandle drive = CreateFile( fileName: FileName,
fileAccess: FileAccess.Read,
fileShare: FileShare.Write | FileShare.Read | FileShare.Delete,
securityAttributes: IntPtr.Zero,
creationDisposition: FileMode.Open,
flags: 4, //with this also an enum can be used. (as described above as EFileAttributes)
template: IntPtr.Zero );
if (drive.IsInvalid) {
throw new IOException( "Unable to access drive. Win32 Error Code " + Marshal.GetLastWin32Error() );
//if get windows error code 5 this means access denied. You must try to run the program as admin privileges.
}
Where is the secutityAttributes?! It's not to uncommon to want a file handle to be inheritable (e.g. you want to pass a handle to a server component like something running as a "servicedComponent" or a service...) and by using the securityAttributes this can be done...
***********
Note that on win98, mapping the parameters to FileAccess and FileShare will cause CreateFileA to fail. I found this out the hard way, banging my head against a very slow win98 machine across an even slow connection. Instead use the EFileAccess, and EFileShare enumeration constants that match the windows constants ( as mentioned earlier in the article ).
An IntPtr is a pointer to a memory location (unmanaged) that adapts to the platform it is running on (64-bit, etc.) UNLIKE a standard int/Integer. You should always use this type for unmanaged calls that require it, even though an int will appear to work on your development machine.
1/13/2008 4:00:13 AM - Damon Carr-72.43.165.29
TODO - a short description
3/16/2007 7:52:17 AM - anonymous
TODO - a short description
3/16/2007 7:52:17 AM - anonymous
Click to read this page
12/2/2010 4:36:50 PM - -81.247.25.174
An IntPtr is a pointer to a memory location (unmanaged) that adapts to the platform it is running on (64-bit, etc.) UNLIKE a standard int/Integer. You should always use this type for unmanaged calls that require it, even though an int will appear to work on your development machine.
1/13/2008 4:00:13 AM - Damon Carr-72.43.165.29
Click to read this page
12/2/2010 4:36:50 PM - -81.247.25.174
Please edit this page!
Do you have...
helpful tips or sample code to share for using this API in managed code?
corrections to the existing content?
variations of the signature you want to share?
additional languages you want to include?
Select "Edit This Page" on the right hand toolbar and edit it! Or add new pages containing supporting types needed for this API (structures, delegates, and more).