/* Copyright (C) 2008-2016 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using Alphaleonis.Win32.Security; using Microsoft.Win32.SafeHandles; using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; using FileStream = System.IO.FileStream; namespace Alphaleonis.Win32.Filesystem { public static partial class File { #region Non-Transactional /// Creates or overwrites a file in the specified path. /// The path and name of the file to create. /// A that provides read/write access to the file specified in . [SecurityCritical] public static FileStream Create(string path) { return CreateFileStreamCore(null, path, ExtendedFileAttributes.Normal, null, FileMode.Create, FileAccess.ReadWrite, FileShare.None, NativeMethods.DefaultFileBufferSize, PathFormat.RelativePath); } /// Creates or overwrites the specified file. /// The name of the file. /// The number of bytes buffered for reads and writes to the file. /// /// A with the specified buffer size that provides read/write access to the file specified in /// . /// [SecurityCritical] public static FileStream Create(string path, int bufferSize) { return CreateFileStreamCore(null, path, ExtendedFileAttributes.Normal, null, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, PathFormat.RelativePath); } /// /// Creates or overwrites the specified file, specifying a buffer size and a /// value that describes how to create or overwrite the file. /// /// The name of the file. /// The number of bytes buffered for reads and writes to the file. /// One of the values that describes how to create or overwrite the file. /// A new file with the specified buffer size. [SecurityCritical] public static FileStream Create(string path, int bufferSize, FileOptions options) { return CreateFileStreamCore(null, path, (ExtendedFileAttributes) options, null, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, PathFormat.RelativePath); } /// /// Creates or overwrites the specified file, specifying a buffer size and a /// value that describes how to create or overwrite the file. /// /// The name of the file. /// The number of bytes buffered for reads and writes to the file. /// One of the values that describes how to create or overwrite the file. /// /// One of the values that determines the access control and audit security for the file. /// /// A new file with the specified buffer size, file options, and file security. [SecurityCritical] public static FileStream Create(string path, int bufferSize, FileOptions options, FileSecurity fileSecurity) { return CreateFileStreamCore(null, path, (ExtendedFileAttributes)options, fileSecurity, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, PathFormat.RelativePath); } /// Creates or overwrites a file in the specified path. /// The path and name of the file to create. /// Indicates the format of the path parameter(s). /// /// A that provides read/write access to the file specified in /// . /// [SecurityCritical] public static FileStream Create(string path, PathFormat pathFormat) { return CreateFileStreamCore(null, path, ExtendedFileAttributes.Normal, null, FileMode.Create, FileAccess.ReadWrite, FileShare.None, NativeMethods.DefaultFileBufferSize, pathFormat); } /// Creates or overwrites the specified file. /// The name of the file. /// The number of bytes buffered for reads and writes to the file. /// Indicates the format of the path parameter(s). /// /// A with the specified buffer size that provides read/write access to the file specified in /// . /// [SecurityCritical] public static FileStream Create(string path, int bufferSize, PathFormat pathFormat) { return CreateFileStreamCore(null, path, ExtendedFileAttributes.Normal, null, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, pathFormat); } /// /// Creates or overwrites the specified file, specifying a buffer size and a /// value that describes how to create or overwrite the file. /// /// The name of the file. /// /// The number of bytes buffered for reads and writes to the file. /// /// /// One of the values that describes how to create or overwrite the /// file. /// /// Indicates the format of the path parameter(s). /// A new file with the specified buffer size. [SecurityCritical] public static FileStream Create(string path, int bufferSize, FileOptions options, PathFormat pathFormat) { return CreateFileStreamCore(null, path, (ExtendedFileAttributes)options, null, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, pathFormat); } /// /// Creates or overwrites the specified file, specifying a buffer size and a /// value that describes how to create or overwrite the file. /// /// The name of the file. /// /// The number of bytes buffered for reads and writes to the file. /// /// /// One of the values that describes how to create or overwrite the /// file. /// /// /// One of the values that determines the access control and audit /// security for the file. /// /// Indicates the format of the path parameter(s). /// /// A new file with the specified buffer size, file options, and file security. /// [SecurityCritical] public static FileStream Create(string path, int bufferSize, FileOptions options, FileSecurity fileSecurity, PathFormat pathFormat) { return CreateFileStreamCore(null, path, (ExtendedFileAttributes)options, fileSecurity, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, pathFormat); } #endregion // .NET #region Transactional /// Creates or overwrites a file in the specified path. /// The transaction. /// The path and name of the file to create. /// /// A that provides read/write access to the file specified in /// . /// [SecurityCritical] public static FileStream CreateTransacted(KernelTransaction transaction, string path) { return CreateFileStreamCore(transaction, path, ExtendedFileAttributes.Normal, null, FileMode.Create, FileAccess.ReadWrite, FileShare.None, NativeMethods.DefaultFileBufferSize, PathFormat.RelativePath); } /// Creates or overwrites the specified file. /// The transaction. /// The name of the file. /// /// The number of bytes buffered for reads and writes to the file. /// /// /// A with the specified buffer size that provides read/write access /// to the file specified in . /// [SecurityCritical] public static FileStream CreateTransacted(KernelTransaction transaction, string path, int bufferSize) { return CreateFileStreamCore(transaction, path, ExtendedFileAttributes.Normal, null, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, PathFormat.RelativePath); } /// /// Creates or overwrites the specified file, specifying a buffer size and a /// value that describes how to create or overwrite the file. /// /// The transaction. /// The name of the file. /// The number of bytes buffered for reads and writes to the file. /// One of the values that describes how to create or overwrite the file. /// A new file with the specified buffer size. [SecurityCritical] public static FileStream CreateTransacted(KernelTransaction transaction, string path, int bufferSize, FileOptions options) { return CreateFileStreamCore(transaction, path, (ExtendedFileAttributes)options, null, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, PathFormat.RelativePath); } /// /// Creates or overwrites the specified file, specifying a buffer size and a /// value that describes how to create or overwrite the file. /// /// The transaction. /// The name of the file. /// The number of bytes buffered for reads and writes to the file. /// One of the values that describes how to create or overwrite the file. /// /// One of the values that determines the access control and audit security for the file. /// /// A new file with the specified buffer size, file options, and file security. [SecurityCritical] public static FileStream CreateTransacted(KernelTransaction transaction, string path, int bufferSize, FileOptions options, FileSecurity fileSecurity) { return CreateFileStreamCore(transaction, path, (ExtendedFileAttributes)options, fileSecurity, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, PathFormat.RelativePath); } /// Creates or overwrites a file in the specified path. /// The transaction. /// The path and name of the file to create. /// Indicates the format of the path parameter(s). /// /// A that provides read/write access to the file specified in /// . /// [SecurityCritical] public static FileStream CreateTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return CreateFileStreamCore(transaction, path, ExtendedFileAttributes.Normal, null, FileMode.Create, FileAccess.ReadWrite, FileShare.None, NativeMethods.DefaultFileBufferSize, pathFormat); } /// Creates or overwrites the specified file. /// The transaction. /// The name of the file. /// The number of bytes buffered for reads and writes to the file. /// Indicates the format of the path parameter(s). /// /// A with the specified buffer size that provides read/write access to the file specified in /// . /// [SecurityCritical] public static FileStream CreateTransacted(KernelTransaction transaction, string path, int bufferSize, PathFormat pathFormat) { return CreateFileStreamCore(transaction, path, ExtendedFileAttributes.Normal, null, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, pathFormat); } /// /// Creates or overwrites the specified file, specifying a buffer size and a /// value that describes how to create or overwrite the file. /// /// The transaction. /// The name of the file. /// The number of bytes buffered for reads and writes to the file. /// One of the values that describes how to create or overwrite the file. /// Indicates the format of the path parameter(s). /// A new file with the specified buffer size. [SecurityCritical] public static FileStream CreateTransacted(KernelTransaction transaction, string path, int bufferSize, FileOptions options, PathFormat pathFormat) { return CreateFileStreamCore(transaction, path, (ExtendedFileAttributes)options, null, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, pathFormat); } /// /// Creates or overwrites the specified file, specifying a buffer size and a /// value that describes how to create or overwrite the file. /// /// The transaction. /// The name of the file. /// The number of bytes buffered for reads and writes to the file. /// One of the values that describes how to create or overwrite the file. /// /// One of the values that determines the access control and audit security for the file. /// /// Indicates the format of the path parameter(s). /// A new file with the specified buffer size, file options, and file security. [SecurityCritical] public static FileStream CreateTransacted(KernelTransaction transaction, string path, int bufferSize, FileOptions options, FileSecurity fileSecurity, PathFormat pathFormat) { return CreateFileStreamCore(transaction, path, (ExtendedFileAttributes)options, fileSecurity, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, pathFormat); } #endregion #region Internal /// Creates or overwrites a file in the specified path. /// The transaction. /// The name of the file. /// The additional advanced options to create a file. /// /// A instance that determines the access control and audit security for the file. /// /// The option gives you more precise control over how you want to create a file. /// /// The allow you additionally specify to default read/write capability - just write, bypassing any cache. /// /// /// The option controls how you would like to share created file with other requesters. /// /// Indicates the format of the parameter. /// The number of bytes buffered for reads and writes to the file. /// A that provides read/write access to the file specified in path. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "False positive")] [SecurityCritical] internal static FileStream CreateFileStreamCore(KernelTransaction transaction, string path, ExtendedFileAttributes attributes, FileSecurity fileSecurity, FileMode mode, FileAccess access, FileShare share, int bufferSize, PathFormat pathFormat) { SafeFileHandle safeHandle = null; try { safeHandle = CreateFileCore(transaction, path, attributes, fileSecurity, mode, (FileSystemRights) access, share, true, pathFormat); return new FileStream(safeHandle, access, bufferSize, (attributes & ExtendedFileAttributes.Overlapped) != 0); } catch { if (safeHandle != null) safeHandle.Dispose(); throw; } } /// Creates or opens a file, directory or I/O device. /// A that provides read/write access to the file or directory specified by . /// /// To obtain a directory handle using CreateFile, specify the FILE_FLAG_BACKUP_SEMANTICS flag as part of dwFlagsAndAttributes. /// 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 transaction. /// The path and name of the file or directory to create. /// One of the values that describes how to create or overwrite the file or directory. /// A instance that determines the access control and audit security for the file or directory. /// A constant that determines how to open or create the file or directory. /// A constant that determines the access rights to use when creating access and audit rules for the file or directory. /// A constant that determines how the file or directory will be shared by processes. /// . /// Indicates the format of the parameter. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object needs to be disposed by caller.")] [SecurityCritical] internal static SafeFileHandle CreateFileCore(KernelTransaction transaction, string path, ExtendedFileAttributes attributes, FileSecurity fileSecurity, FileMode fileMode, FileSystemRights fileSystemRights, FileShare fileShare, bool checkPath, PathFormat pathFormat) { if (checkPath && pathFormat == PathFormat.RelativePath) Path.CheckSupportedPathFormat(path, true, true); // When isFile == null, we're working with a device. // When opening a VOLUME or removable media drive (for example, a floppy disk drive or flash memory thumb drive), // the path string should be the following form: "\\.\X:" // Do not use a trailing backslash (\), which indicates the root. var pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator); PrivilegeEnabler privilegeEnabler = null; var isAppend = fileMode == FileMode.Append; // CreateFileXxx() does not support FileMode.Append mode. if (isAppend) { fileMode = FileMode.OpenOrCreate; fileSystemRights &= FileSystemRights.AppendData; // Add right. } if (fileSecurity != null) fileSystemRights |= (FileSystemRights) 0x1000000; // Set right. // AccessSystemSecurity = 0x1000000 AccessSystemAcl access type. // MaximumAllowed = 0x2000000 MaximumAllowed access type. if ((fileSystemRights & (FileSystemRights) 0x1000000) != 0 || (fileSystemRights & (FileSystemRights) 0x2000000) != 0) privilegeEnabler = new PrivilegeEnabler(Privilege.Security); using (privilegeEnabler) using (var securityAttributes = new Security.NativeMethods.SecurityAttributes(fileSecurity)) { var handle = transaction == null || !NativeMethods.IsAtLeastWindowsVista // CreateFile() / CreateFileTransacted() // 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. // 2013-01-13: MSDN confirms LongPath usage. ? NativeMethods.CreateFile(pathLp, fileSystemRights, fileShare, securityAttributes, fileMode, attributes, IntPtr.Zero) : NativeMethods.CreateFileTransacted(pathLp, fileSystemRights, fileShare, securityAttributes, fileMode, attributes, IntPtr.Zero, transaction.SafeHandle, IntPtr.Zero, IntPtr.Zero); var lastError = Marshal.GetLastWin32Error(); if (handle.IsInvalid) { handle.Close(); NativeError.ThrowException(lastError, pathLp); } if (isAppend) { var stream = new FileStream(handle, FileAccess.Write, NativeMethods.DefaultFileBufferSize, (attributes & ExtendedFileAttributes.Overlapped) != 0); stream.Seek(0, SeekOrigin.End); } return handle; } } #endregion // CreateFileCore } }