internal static void EncryptDecryptFileInternal(bool isFolder, string path, bool encrypt, PathFormat pathFormat) { string pathLp = Path.GetExtendedLengthPathInternal(null, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck); // Reset file/directory attributes. // MSDN: If lpFileName specifies a read-only file, the function fails and GetLastError returns ERROR_FILE_READ_ONLY. SetAttributesInternal(isFolder, null, pathLp, FileAttributes.Normal, true, PathFormat.LongFullPath); // EncryptFile() / DecryptFile() // In the ANSI version of this function, the name is limited to 248 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 does not confirm LongPath usage but a Unicode version of this function exists. if (!(encrypt ? NativeMethods.EncryptFile(pathLp) : NativeMethods.DecryptFile(pathLp, 0))) { int lastError = Marshal.GetLastWin32Error(); switch ((uint)lastError) { case Win32Errors.ERROR_ACCESS_DENIED: string root = Path.GetPathRoot(pathLp, false); if (!string.Equals("NTFS", new DriveInfo(root).DriveFormat, StringComparison.OrdinalIgnoreCase)) throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "The drive does not support NTFS encryption: [{0}]", root)); break; default: if (lastError == Win32Errors.ERROR_FILE_NOT_FOUND && isFolder) lastError = (int)Win32Errors.ERROR_PATH_NOT_FOUND; NativeError.ThrowException(lastError, pathLp); break; } } }
internal static IEnumerable<AlternateDataStreamInfo> EnumerateAlternateDataStreamsInternal(KernelTransaction transaction, string path, PathFormat pathFormat) { using (var buffer = new SafeGlobalMemoryBufferHandle(Marshal.SizeOf(typeof(NativeMethods.WIN32_FIND_STREAM_DATA)))) { path = Path.GetExtendedLengthPathInternal(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.CheckInvalidPathChars | GetFullPathOptions.CheckAdditional); using (var handle = transaction == null ? NativeMethods.FindFirstStreamW(path, NativeMethods.StreamInfoLevels.FindStreamInfoStandard, buffer, 0) : NativeMethods.FindFirstStreamTransactedW(path, NativeMethods.StreamInfoLevels.FindStreamInfoStandard, buffer, 0, transaction.SafeHandle)) { if (handle.IsInvalid) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Win32Errors.ERROR_HANDLE_EOF) yield break; NativeError.ThrowException(errorCode); } while (true) { NativeMethods.WIN32_FIND_STREAM_DATA data = buffer.PtrToStructure<NativeMethods.WIN32_FIND_STREAM_DATA>(); yield return new AlternateDataStreamInfo(path, data); if (!NativeMethods.FindNextStreamW(handle, buffer)) { int lastError = Marshal.GetLastWin32Error(); if (lastError == Win32Errors.ERROR_HANDLE_EOF) break; NativeError.ThrowException(lastError, path); } } } } }
internal static DirectoryInfo GetParentInternal(KernelTransaction transaction, string path, PathFormat pathFormat) { string pathLp = Path.GetExtendedLengthPathInternal(transaction, path, pathFormat, GetFullPathOptions.CheckInvalidPathChars); pathLp = Path.GetRegularPathInternal(pathLp, GetFullPathOptions.None); string dirName = Path.GetDirectoryName(pathLp, false); return Utils.IsNullOrWhiteSpace(dirName) ? null : new DirectoryInfo(transaction, dirName, PathFormat.RelativePath); }
public void Parse(DirectoryInfo moaiSourceDirectory, PathFormat messagePathFormat) { // Check that the input directory looks like the Moai src directory if (!moaiSourceDirectory.GetDirectoryInfo("moai-core").Exists) { throw new ApplicationException(string.Format("Path '{0}' does not appear to be the 'src' directory of a Moai source copy.", moaiSourceDirectory)); } // Initialize type list with primitive types typesByName = new Dictionary<string, MoaiType>(); var primitiveTypeNames = new[] { "nil", "boolean", "number", "string", "userdata", "function", "thread", "table" }; foreach (string primitiveTypeName in primitiveTypeNames) { typesByName[primitiveTypeName] = new MoaiType { Name = primitiveTypeName, IsPrimitive = true }; } // Parse Moai types and store them by type name log.Info("Parsing Moai types."); ParseMoaiCodeFiles(moaiSourceDirectory, messagePathFormat); // MOAILuaObject is not documented, probably because it would mess up // the Doxygen-generated documentation. Use dummy code instead. log.Info("Adding hard-coded documentation for MoaiLuaObject base class."); FilePosition dummyFilePosition = new FilePosition(new FileInfo("MoaiLuaObject dummy code"), new DirectoryInfo("."), messagePathFormat); ParseMoaiFile(MoaiLuaObject.DummyCode, dummyFilePosition); // Make sure every class directly or indirectly inherits from MOAILuaObject MoaiType moaiLuaObjectType = GetOrCreateType("MOAILuaObject", null); foreach (MoaiType type in typesByName.Values) { if (!(type.AncestorTypes.Contains(moaiLuaObjectType)) && type != moaiLuaObjectType) { type.BaseTypes.Add(moaiLuaObjectType); } } // Check if we have information on all referenced classes IEnumerable<MoaiType> typesReferencedInDocumentation = typesByName.Values .Where(type => type.DocumentationReferences.Any()); foreach (MoaiType type in typesReferencedInDocumentation.ToArray()) { WarnIfSpeculative(type); } log.Info("Creating compact method signatures."); foreach (MoaiType type in typesByName.Values) { foreach (MoaiMethod method in type.Members.OfType<MoaiMethod>()) { if (!method.Overloads.Any()) { log.WarnFormat("No method documentation found. [{0}]", method.MethodPosition); continue; } try { method.InParameterSignature = GetCompactSignature(method.Overloads.Select(overload => overload.InParameters.ToArray())); method.OutParameterSignature = GetCompactSignature(method.Overloads.Select(overload => overload.OutParameters.ToArray())); } catch (Exception e) { log.WarnFormat("Error determining method signature. {0} [{1}]", e.Message, method.MethodPosition); } } } }
/// <summary>[AlphaFS] Check if the directory has permission inheritance enabled.</summary> /// <returns><see langword="true"/> if permission inheritance is enabled, <see langword="false"/> if permission inheritance is disabled.</returns> /// <param name="path">The full path to the directory to check.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> public static bool HasInheritedPermissions(string path, PathFormat pathFormat) { if (Utils.IsNullOrWhiteSpace(path)) throw new ArgumentNullException("path"); //DirectorySecurity acl = GetAccessControl(directoryPath); DirectorySecurity acl = File.GetAccessControlInternal<DirectorySecurity>(true, path, AccessControlSections.Access | AccessControlSections.Group | AccessControlSections.Owner, pathFormat); return acl.GetAccessRules(false, true, typeof(SecurityIdentifier)).Count > 0; }
public FileInfo Replace(string destinationFileName, string destinationBackupFileName, PathFormat pathFormat) { var options = GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck; string destinationFileNameLp = Path.GetExtendedLengthPathInternal(Transaction, destinationFileName, pathFormat, options); string destinationBackupFileNameLp = Path.GetExtendedLengthPathInternal(Transaction, destinationBackupFileName, pathFormat, options); File.ReplaceInternal(LongFullName, destinationFileNameLp, destinationBackupFileNameLp, false, PathFormat.LongFullPath); return new FileInfo(Transaction, destinationFileNameLp, PathFormat.LongFullPath); }
/// <summary>Initializes a Shell32Info instance. /// <remarks>Shell32 is limited to MAX_PATH length.</remarks> /// <remarks>This constructor does not check if a file exists. This constructor is a placeholder for a string that is used to access the file in subsequent operations.</remarks> /// </summary> /// <param name="fileName">The fully qualified name of the new file, or the relative file name. Do not end the path with the directory separator character.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> public Shell32Info(string fileName, PathFormat pathFormat) { if (Utils.IsNullOrWhiteSpace(fileName)) throw new ArgumentNullException("fileName"); // Shell32 is limited to MAX_PATH length. // Get a full path of regular format. FullPath = Path.GetExtendedLengthPathInternal(null, fileName, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck); Initialize(); }
internal static FileEncryptionStatus GetEncryptionStatusInternal(string path, PathFormat pathFormat) { if (pathFormat != PathFormat.LongFullPath && Utils.IsNullOrWhiteSpace(path)) throw new ArgumentNullException("path"); string pathLp = Path.GetExtendedLengthPathInternal(null, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck); FileEncryptionStatus status; // FileEncryptionStatus() // In the ANSI version of this function, the name is limited to 248 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 does not confirm LongPath usage but a Unicode version of this function exists. if (!NativeMethods.FileEncryptionStatus(pathLp, out status)) NativeError.ThrowException(Marshal.GetLastWin32Error(), pathLp); return status; }
public static void Copy(KernelTransaction transaction, string sourceFileName, string destinationFileName, CopyOptions copyOptions, bool preserveDates, PathFormat pathFormat) { CopyMoveInternal(false, transaction, sourceFileName, destinationFileName, preserveDates, copyOptions, null, null, null, pathFormat); }
internal static void DeleteEmptySubdirectoriesCore(FileSystemEntryInfo fsEntryInfo, KernelTransaction transaction, string path, bool recursive, bool ignoreReadOnly, PathFormat pathFormat) { #region Setup if (null == fsEntryInfo) { if (pathFormat == PathFormat.RelativePath) { Path.CheckSupportedPathFormat(path, true, true); } if (!File.ExistsCore(transaction, true, path, pathFormat)) { NativeError.ThrowException(Win32Errors.ERROR_PATH_NOT_FOUND, path); } fsEntryInfo = File.GetFileSystemEntryInfoCore(transaction, true, Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck), false, pathFormat); if (null == fsEntryInfo) { return; } } #endregion // Setup // Ensure path is a directory. if (!fsEntryInfo.IsDirectory) { throw new IOException(string.Format(CultureInfo.InvariantCulture, Resources.Target_Directory_Is_A_File, fsEntryInfo.LongFullPath)); } var dirs = new Stack <string>(1000); dirs.Push(fsEntryInfo.LongFullPath); while (dirs.Count > 0) { foreach (var fsei in EnumerateFileSystemEntryInfosCore <FileSystemEntryInfo>(true, transaction, dirs.Pop(), Path.WildcardStarMatchAll, null, DirectoryEnumerationOptions.ContinueOnException, null, PathFormat.LongFullPath)) { // Ensure the directory is empty. if (IsEmptyCore(transaction, fsei.LongFullPath, pathFormat)) { DeleteDirectoryCore(transaction, fsei, null, false, ignoreReadOnly, true, PathFormat.LongFullPath); } else if (recursive) { dirs.Push(fsei.LongFullPath); } } } }
/// <summary>Gets the path as a long full path.</summary> /// <returns>The path as an extended length path.</returns> /// <exception cref="ArgumentException"/> /// <param name="transaction">The transaction.</param> /// <param name="sourcePath">Full pathname of the source path to convert.</param> /// <param name="pathFormat">The path format to use.</param> /// <param name="options">Options for controlling the operation. Note that on .NET 3.5 the TrimEnd option has no effect.</param> internal static string GetExtendedLengthPathCore(KernelTransaction transaction, string sourcePath, PathFormat pathFormat, GetFullPathOptions options) { switch (pathFormat) { case PathFormat.LongFullPath: return(sourcePath); case PathFormat.FullPath: return(GetLongPathCore(sourcePath, GetFullPathOptions.None)); case PathFormat.RelativePath: #if NET35 // .NET 3.5 the TrimEnd option has no effect. options = options & ~GetFullPathOptions.TrimEnd; #endif return(GetFullPathCore(transaction, sourcePath, GetFullPathOptions.AsLongPath | options)); default: throw new ArgumentException("Invalid value for " + typeof(PathFormat).Name + ": " + pathFormat); } }
public static void DeleteEmptySubdirectoriesTransacted(KernelTransaction transaction, string path, bool recursive, bool ignoreReadOnly, PathFormat pathFormat) { DeleteEmptySubdirectoriesCore(null, transaction, path, recursive, ignoreReadOnly, pathFormat); }
public static string ReadAllText(string path, Encoding encoding, PathFormat pathFormat) { return ReadAllTextInternal(null, path, encoding, pathFormat); }
private void ParseMoaiCodeFiles(DirectoryInfo moaiSourceDirectory, PathFormat messagePathFormat) { IEnumerable<FileInfo> codeFiles = Directory .EnumerateFiles(moaiSourceDirectory.FullName, "*.*", SearchOption.AllDirectories) .Where(name => name.EndsWith(".cpp") || name.EndsWith(".h")) .Select(name => new FileInfo(name)); foreach (var codeFile in codeFiles) { FilePosition filePosition = new FilePosition(codeFile, moaiSourceDirectory, messagePathFormat); ParseMoaiCodeFile(codeFile, filePosition); } }
public static string[] ReadAllLines(KernelTransaction transaction, string path, Encoding encoding, PathFormat pathFormat) { return ReadAllLinesInternal(transaction, path, encoding, pathFormat).ToArray(); }
public static bool ExistsTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return(ExistsCore(false, transaction, path, pathFormat)); }
public static void Delete(string path, bool recursive, PathFormat pathFormat) { DeleteDirectoryCore(null, null, path, recursive, false, false, pathFormat); }
internal static void DeleteDirectoryCore(FileSystemEntryInfo fsEntryInfo, KernelTransaction transaction, string path, bool recursive, bool ignoreReadOnly, bool continueOnNotFound, PathFormat pathFormat) { #region Setup if (fsEntryInfo == null) { // MSDN: .NET 3.5+: DirectoryNotFoundException: // Path does not exist or could not be found. // Path refers to a file instead of a directory. // The specified path is invalid (for example, it is on an unmapped drive). if (pathFormat == PathFormat.RelativePath) { Path.CheckSupportedPathFormat(path, true, true); } fsEntryInfo = File.GetFileSystemEntryInfoCore(true, transaction, Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator), continueOnNotFound, pathFormat); if (fsEntryInfo == null) { return; } } #endregion // Setup // Do not follow mount points nor symbolic links, but do delete the reparse point itself. // If directory is reparse point, disable recursion. if (recursive && !fsEntryInfo.IsReparsePoint) { var dirs = new Stack <string>(1000); foreach (var fsei in EnumerateFileSystemEntryInfosCore <FileSystemEntryInfo>(transaction, fsEntryInfo.LongFullPath, Path.WildcardStarMatchAll, DirectoryEnumerationOptions.FilesAndFolders | DirectoryEnumerationOptions.Recursive, PathFormat.LongFullPath)) { if (fsei.IsDirectory) { // Check to see if this is a mount point, and unmount it. // Now it is safe to delete the actual directory. if (fsei.IsMountPoint) { Volume.DeleteVolumeMountPointCore(fsei.LongFullPath, false); } dirs.Push(fsei.LongFullPath); } else { File.DeleteFileCore(transaction, fsei.LongFullPath, ignoreReadOnly, PathFormat.LongFullPath); } } while (dirs.Count > 0) { DeleteDirectoryCore(transaction, dirs.Pop(), ignoreReadOnly, continueOnNotFound); } } // Check to see if this is a mount point, and unmount it. // Now it is safe to delete the actual directory. if (fsEntryInfo.IsMountPoint) { Volume.DeleteVolumeMountPointCore(fsEntryInfo.LongFullPath, false); } DeleteDirectoryCore(transaction, fsEntryInfo.LongFullPath, ignoreReadOnly, continueOnNotFound); }
public static void DeleteTransacted(KernelTransaction transaction, string path, bool recursive, bool ignoreReadOnly, PathFormat pathFormat) { DeleteDirectoryCore(null, transaction, path, recursive, ignoreReadOnly, false, pathFormat); }
public static void DeleteTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { DeleteDirectoryCore(null, transaction, path, false, false, false, pathFormat); }
internal static void ToggleCompressionCore(bool isFolder, KernelTransaction transaction, string path, bool compress, PathFormat pathFormat) { using (SafeFileHandle handle = File.CreateFileCore(transaction, path, isFolder ? ExtendedFileAttributes.BackupSemantics : ExtendedFileAttributes.Normal, null, FileMode.Open, FileSystemRights.Modify, FileShare.None, true, pathFormat)) { // DeviceIoControlMethod.Buffered = 0, // DeviceIoControlFileDevice.FileSystem = 9 // FsctlSetCompression = (DeviceIoControlFileDevice.FileSystem << 16) | (16 << 2) | DeviceIoControlMethod.Buffered | ((FileAccess.Read | FileAccess.Write) << 14) // 0 = Decompress, 1 = Compress. InvokeIoControlUnknownSize(handle, ((9 << 16) | (16 << 2) | 0 | ((uint)(FileAccess.Read | FileAccess.Write) << 14)), (compress) ? 1 : 0); } }
public static void Move(string sourceFileName, string destinationFileName, PathFormat pathFormat) { CopyMoveInternal(false, null, sourceFileName, destinationFileName, false, null, MoveOptions.CopyAllowed, null, null, pathFormat); }
public static void Move(KernelTransaction transaction, string sourceFileName, string destinationFileName, MoveOptions moveOptions, PathFormat pathFormat) { CopyMoveInternal(false, transaction, sourceFileName, destinationFileName, false, null, moveOptions, null, null, pathFormat); }
internal static bool ExistsCore(bool isFolder, KernelTransaction transaction, string path, PathFormat pathFormat) { // Will be caught later and be thrown as an ArgumentException or ArgumentNullException. // Let's take a shorter route, preventing an Exception from being thrown altogether. if (Utils.IsNullOrWhiteSpace(path)) { return(false); } // DriveInfo.IsReady() will fail. // //// After normalizing, check whether path ends in directory separator. //// Otherwise, FillAttributeInfoCore removes it and we may return a false positive. //string pathRp = Path.GetRegularPathCore(path, true, false, false, false); //if (pathRp.Length > 0 && Path.IsDVsc(pathRp[pathRp.Length - 1], false)) // return false; try { string pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.CheckInvalidPathChars | GetFullPathOptions.ContinueOnNonExist); var data = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA(); int dataInitialised = FillAttributeInfoCore(transaction, pathLp, ref data, false, true); return(dataInitialised == Win32Errors.ERROR_SUCCESS && data.dwFileAttributes != (FileAttributes)(-1) && (isFolder ? (data.dwFileAttributes & FileAttributes.Directory) == FileAttributes.Directory : (data.dwFileAttributes & FileAttributes.Directory) != FileAttributes.Directory)); } catch { return(false); } }
public static string[] ReadAllLines(string path, PathFormat pathFormat) { return ReadAllLinesInternal(null, path, NativeMethods.DefaultFileEncoding, pathFormat).ToArray(); }
public static bool Exists(string path, PathFormat pathFormat) { return(ExistsCore(false, null, path, pathFormat)); }
public static StreamWriter CreateText(string path, PathFormat pathFormat) { return(CreateTextCore(null, path, NativeMethods.DefaultFileEncoding, pathFormat)); }
/// <summary>[AlphaFS] Restores (import) encrypted files. This is one of a group of Encrypted File System (EFS) functions that is /// intended to implement backup and restore functionality, while maintaining files in their encrypted state.</summary> /// <remarks> /// <para> /// If the caller does not have access to the key for the file, the caller needs /// <see cref="Alphaleonis.Win32.Security.Privilege.Backup"/> to restore encrypted files. See /// <see cref="Alphaleonis.Win32.Security.PrivilegeEnabler"/>. /// </para> /// <para> /// To restore an encrypted file call one of the /// <see cref="O:Alphaleonis.Win32.Filesystem.File.ImportEncryptedFileRaw"/> overloads and specify the file to restore /// along with the destination stream of the restored data. /// </para> /// <para> /// This function is intended for the restoration of only encrypted files; see <see cref="BackupFileStream"/> for /// backup of unencrypted files. /// </para> /// </remarks> /// <param name="inputStream">The stream to read previously backed up data from.</param> /// <param name="destinationFilePath">The path of the destination file to restore to.</param> /// <param name="overwriteHidden">If set to <see langword="true"/> a hidden file will be overwritten on import.</param> /// <param name="pathFormat">The path format of the <paramref name="destinationFilePath"/> parameter.</param> /// <seealso cref="O:Alphaleonis.Win32.Filesystem.File.ExportEncryptedFileRaw"/> public static void ImportEncryptedFileRaw(Stream inputStream, string destinationFilePath, bool overwriteHidden, PathFormat pathFormat) { ImportExportEncryptedFileDirectoryRawCore(false, false, inputStream, destinationFilePath, pathFormat, overwriteHidden); }
public static void Delete(string path, bool ignoreReadOnly, PathFormat pathFormat) { DeleteFileInternal(null, path, ignoreReadOnly, pathFormat); }
public static StreamWriter CreateText(string path, Encoding encoding, PathFormat pathFormat) { return(CreateTextCore(null, path, encoding, pathFormat)); }
internal static void ImportExportEncryptedFileDirectoryRawCore(bool isExport, bool isFolder, Stream stream, string destinationPath, PathFormat pathFormat, bool overwriteHidden) { string destinationPathLp = Path.GetExtendedLengthPathCore(null, destinationPath, pathFormat, GetFullPathOptions.FullCheck | GetFullPathOptions.TrimEnd); NativeMethods.EncryptedFileRawMode mode = isExport ? NativeMethods.EncryptedFileRawMode.CreateForExport : NativeMethods.EncryptedFileRawMode.CreateForImport; if (isFolder) { mode = mode | NativeMethods.EncryptedFileRawMode.CreateForDir; } if (overwriteHidden) { mode = mode | NativeMethods.EncryptedFileRawMode.OverwriteHidden; } // OpenEncryptedFileRaw() // 2015-08-02: MSDN does not confirm LongPath usage but a Unicode version of this function exists. SafeEncryptedFileRawHandle context; var lastError = NativeMethods.OpenEncryptedFileRaw(destinationPathLp, mode, out context); try { if (lastError != Win32Errors.ERROR_SUCCESS) { NativeError.ThrowException(lastError, destinationPathLp); } lastError = isExport ? NativeMethods.ReadEncryptedFileRaw((pbData, pvCallbackContext, length) => { try { var data = new byte[length]; Marshal.Copy(pbData, data, 0, (int)length); stream.Write(data, 0, (int)length); } catch (Exception ex) { return(Marshal.GetHRForException(ex) & NativeMethods.OverflowExceptionBitShift); } return((int)Win32Errors.ERROR_SUCCESS); }, IntPtr.Zero, context) : NativeMethods.WriteEncryptedFileRaw((IntPtr pbData, IntPtr pvCallbackContext, ref uint length) => { try { var data = new byte[length]; length = (uint)stream.Read(data, 0, (int)length); if (length == 0) { return((int)Win32Errors.ERROR_SUCCESS); } Marshal.Copy(data, 0, pbData, (int)length); } catch (Exception ex) { return(Marshal.GetHRForException(ex) & NativeMethods.OverflowExceptionBitShift); } return((int)Win32Errors.ERROR_SUCCESS); }, IntPtr.Zero, context); if (lastError != Win32Errors.ERROR_SUCCESS) { NativeError.ThrowException(lastError, destinationPathLp); } } finally { if (context != null) { context.Dispose(); } } }
public static StreamWriter CreateTextTransacted(KernelTransaction transaction, string path, Encoding encoding, PathFormat pathFormat) { return(CreateTextCore(transaction, path, encoding, pathFormat)); }
public static void DeleteEmptySubdirectories(string path, bool recursive, PathFormat pathFormat) { DeleteEmptySubdirectoriesCore(null, null, path, recursive, false, pathFormat); }
/// <summary>[AlphaFS] Backs up (export) encrypted files. This is one of a group of Encrypted File System (EFS) functions that is /// intended to implement backup and restore functionality, while maintaining files in their encrypted state.</summary> /// <remarks> /// <para> /// The file being backed up is not decrypted; it is backed up in its encrypted state. /// </para> /// <para> /// If the caller does not have access to the key for the file, the caller needs /// <see cref="Alphaleonis.Win32.Security.Privilege.Backup"/> to export encrypted files. See /// <see cref="Alphaleonis.Win32.Security.PrivilegeEnabler"/>. /// </para> /// <para> /// To backup an encrypted file call one of the /// <see cref="O:Alphaleonis.Win32.Filesystem.File.ExportEncryptedFileRaw"/> overloads and specify the file to backup /// along with the destination stream of the backup data. /// </para> /// <para> /// This function is intended for the backup of only encrypted files; see <see cref="BackupFileStream"/> for backup /// of unencrypted files. /// </para> /// </remarks> /// <param name="fileName">The name of the file to be backed up.</param> /// <param name="outputStream">The destination stream to which the backup data will be written.</param> /// <param name="pathFormat">The path format of the <paramref name="fileName"/> parameter.</param> /// <seealso cref="O:Alphaleonis.Win32.Filesystem.File.ImportEncryptedFileRaw"/> public static void ExportEncryptedFileRaw(string fileName, Stream outputStream, PathFormat pathFormat) { ImportExportEncryptedFileDirectoryRawCore(true, false, outputStream, fileName, pathFormat, false); }
public static IEnumerable <AlternateDataStreamInfo> EnumerateAlternateDataStreams(string path, PathFormat pathFormat) { return(File.EnumerateAlternateDataStreamsCore(null, true, path, pathFormat)); }
public static IEnumerable <AlternateDataStreamInfo> EnumerateAlternateDataStreamsTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return(File.EnumerateAlternateDataStreamsCore(transaction, true, path, pathFormat)); }
public static void Copy(string sourceFileName, string destinationFileName, CopyOptions copyOptions, PathFormat pathFormat) { CopyMoveInternal(false, null, sourceFileName, destinationFileName, false, copyOptions, null, null, null, pathFormat); }
/// <summary>[AlphaFS] Gets a list of processes that have a lock on the file(s) specified by <paramref name="filePaths"/>. /// <para> </para> /// <returns> /// <para>Returns null when no processes found that are locking the file(s) specified by <paramref name="filePaths"/>.</para> /// <para>Returns a list of processes locking the file(s) specified by <paramref name="filePaths"/>.</para> /// </returns> /// </summary> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="ArgumentOutOfRangeException"/> /// <exception cref="InvalidOperationException"/> /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception> /// <param name="filePaths">A list with one or more file paths.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> public static Collection <Process> GetProcessForFileLock(Collection <string> filePaths, PathFormat pathFormat) { return(GetProcessForFileLockCore(null, filePaths, pathFormat)); }
public static CopyMoveResult Copy(KernelTransaction transaction, string sourceFileName, string destinationFileName, CopyOptions copyOptions, bool preserveDates, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveInternal(false, transaction, sourceFileName, destinationFileName, preserveDates, copyOptions, null, progressHandler, userProgressData, pathFormat); }
/// <summary>[AlphaFS] Gets a list of processes that have a lock on the files specified by <paramref name="filePath"/>. /// <para> </para> /// <returns> /// <para>Returns null when no processes found that are locking the file specified by <paramref name="filePath"/>.</para> /// <para>Returns a list of processes locking the file specified by <paramref name="filePath"/>.</para> /// </returns> /// </summary> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="ArgumentOutOfRangeException"/> /// <exception cref="InvalidOperationException"/> /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception> /// <param name="transaction">The transaction.</param> /// <param name="filePath">The path to the file.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> public static Collection <Process> GetProcessForFileLockTransacted(KernelTransaction transaction, string filePath, PathFormat pathFormat) { return(GetProcessForFileLockCore(transaction, new Collection <string>(new[] { filePath }), pathFormat)); }
public static CopyMoveResult Move(string sourceFileName, string destinationFileName, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { return CopyMoveInternal(false, null, sourceFileName, destinationFileName, false, null, moveOptions, progressHandler, userProgressData, pathFormat); }
/// <summary>[AlphaFS] Gets a list of processes that have a lock on the file(s) specified by <paramref name="filePaths"/>. /// <para> </para> /// <returns> /// <para>Returns null when no processes found that are locking the file(s) specified by <paramref name="filePaths"/>.</para> /// <para>Returns a list of processes locking the file(s) specified by <paramref name="filePaths"/>.</para> /// </returns> /// </summary> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="ArgumentOutOfRangeException"/> /// <exception cref="InvalidOperationException"/> /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception> /// <param name="transaction">The transaction.</param> /// <param name="filePaths">A list with one or more file paths.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> public static Collection <Process> GetProcessForFileLockTransacted(KernelTransaction transaction, Collection <string> filePaths, PathFormat pathFormat) { return(GetProcessForFileLockCore(transaction, filePaths, pathFormat)); }
public static string[] ReadAllLines(KernelTransaction transaction, string path, PathFormat pathFormat) { return ReadAllLinesInternal(transaction, path, NativeMethods.DefaultFileEncoding, pathFormat).ToArray(); }
public static long CountFileSystemObjects(string path, DirectoryEnumerationOptions options, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosInternal<string>(null, path, Path.WildcardStarMatchAll, options, pathFormat).Count(); }
internal static IEnumerable<string> ReadAllLinesInternal(KernelTransaction transaction, string path, Encoding encoding, PathFormat pathFormat) { using (StreamReader sr = new StreamReader(OpenInternal(transaction, path, FileMode.Open, 0, FileAccess.Read, FileShare.Read, ExtendedFileAttributes.SequentialScan, pathFormat), encoding)) { string line; while ((line = sr.ReadLine()) != null) yield return line; } }
public static string ReadAllText(KernelTransaction transaction, string path, PathFormat pathFormat) { return ReadAllTextInternal(transaction, path, NativeMethods.DefaultFileEncoding, pathFormat); }
public static string[] ReadAllLines(string path, Encoding encoding, PathFormat pathFormat) { return ReadAllLinesInternal(null, path, encoding, pathFormat).ToArray(); }
internal static string ReadAllTextInternal(KernelTransaction transaction, string path, Encoding encoding, PathFormat pathFormat) { using (StreamReader sr = new StreamReader(OpenInternal(transaction, path, FileMode.Open, 0, FileAccess.Read, FileShare.Read, ExtendedFileAttributes.SequentialScan, pathFormat), encoding)) return sr.ReadToEnd(); }
internal static Collection <Process> GetProcessForFileLockCore(KernelTransaction transaction, Collection <string> filePaths, PathFormat pathFormat) { if (!NativeMethods.IsAtLeastWindowsVista) { throw new PlatformNotSupportedException(new Win32Exception((int)Win32Errors.ERROR_OLD_WIN_VERSION).Message); } if (null == filePaths) { throw new ArgumentNullException("filePaths"); } if (filePaths.Count == 0) { throw new ArgumentOutOfRangeException("filePaths", "No paths specified."); } var isLongPath = pathFormat == PathFormat.LongFullPath; var allPaths = isLongPath ? new Collection <string>(filePaths) : new Collection <string>(); if (!isLongPath) { foreach (var path in filePaths) { allPaths.Add(Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck)); } } uint sessionHandle; var success = NativeMethods.RmStartSession(out sessionHandle, 0, Guid.NewGuid().ToString()) == Win32Errors.ERROR_SUCCESS; var lastError = Marshal.GetLastWin32Error(); if (!success) { NativeError.ThrowException(lastError); } var processes = new Collection <Process>(); try { // A snapshot count of all running processes. var processesFound = (uint)Process.GetProcesses().Length; uint lpdwRebootReasons = 0; success = NativeMethods.RmRegisterResources(sessionHandle, (uint)allPaths.Count, allPaths.ToArray(), 0, null, 0, null) == Win32Errors.ERROR_SUCCESS; lastError = Marshal.GetLastWin32Error(); if (!success) { NativeError.ThrowException(lastError); } GetList: var processInfo = new NativeMethods.RM_PROCESS_INFO[processesFound]; var processesTotal = processesFound; lastError = NativeMethods.RmGetList(sessionHandle, out processesFound, ref processesTotal, processInfo, ref lpdwRebootReasons); // There would be no need for this because we already have a/the total number of running processes. if (lastError == Win32Errors.ERROR_MORE_DATA) { goto GetList; } if (lastError != Win32Errors.ERROR_SUCCESS) { NativeError.ThrowException(lastError); } for (var i = 0; i < processesTotal; i++) { try { processes.Add(Process.GetProcessById(processInfo[i].Process.dwProcessId)); } // MSDN: The process specified by the processId parameter is not running. The identifier might be expired. catch (ArgumentException) {} } } finally { NativeMethods.RmEndSession(sessionHandle); } return(processes.Count == 0 ? null : processes); }
internal static StreamWriter CreateTextCore(KernelTransaction transaction, string path, Encoding encoding, PathFormat pathFormat) { return(new StreamWriter(CreateFileStreamCore(transaction, path, ExtendedFileAttributes.SequentialScan, null, FileMode.Create, FileAccess.Write, FileShare.Read, NativeMethods.DefaultFileBufferSize, pathFormat), encoding)); }
public static long CountFileSystemObjects(string path, string searchPattern, DirectoryEnumerationOptions options, PathFormat pathFormat) { return EnumerateFileSystemEntryInfosInternal<string>(null, path, searchPattern, options, pathFormat).Count(); }
/// <summary>[AlphaFS] Gets a list of processes that have a lock on the files specified by <paramref name="filePath"/>. /// <para> </para> /// <returns> /// <para>Returns null when no processes found that are locking the file specified by <paramref name="filePath"/>.</para> /// <para>Returns a list of processes locking the file specified by <paramref name="filePath"/>.</para> /// </returns> /// </summary> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="ArgumentOutOfRangeException"/> /// <exception cref="InvalidOperationException"/> /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception> /// <param name="filePath">The path to the file.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> public static Collection <Process> GetProcessForFileLock(string filePath, PathFormat pathFormat) { return(GetProcessForFileLockCore(null, new Collection <string>(new[] { filePath }), pathFormat)); }
public static string ReadAllText(KernelTransaction transaction, string path, Encoding encoding, PathFormat pathFormat) { return ReadAllTextInternal(transaction, path, encoding, pathFormat); }
public static void DeleteTransacted(KernelTransaction transaction, string path, bool ignoreReadOnly, PathFormat pathFormat) { DeleteFileCore(transaction, path, ignoreReadOnly, pathFormat); }
public static string ReadAllText(string path, PathFormat pathFormat) { return ReadAllTextInternal(null, path, NativeMethods.DefaultFileEncoding, pathFormat); }
internal static void DeleteFileCore(KernelTransaction transaction, string path, bool ignoreReadOnly, PathFormat pathFormat) { #region Setup if (pathFormat == PathFormat.RelativePath) { Path.CheckSupportedPathFormat(path, true, true); } string pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator); // If the path points to a symbolic link, the symbolic link is deleted, not the target. #endregion // Setup startDeleteFile: if (!(transaction == null || !NativeMethods.IsAtLeastWindowsVista // DeleteFile() / DeleteFileTransacted() // 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.DeleteFile(pathLp) : NativeMethods.DeleteFileTransacted(pathLp, transaction.SafeHandle))) { int lastError = Marshal.GetLastWin32Error(); switch ((uint)lastError) { case Win32Errors.ERROR_FILE_NOT_FOUND: // MSDN: .NET 3.5+: If the file to be deleted does not exist, no exception is thrown. return; case Win32Errors.ERROR_PATH_NOT_FOUND: // MSDN: .NET 3.5+: DirectoryNotFoundException: The specified path is invalid (for example, it is on an unmapped drive). NativeError.ThrowException(lastError, pathLp); return; case Win32Errors.ERROR_SHARING_VIOLATION: // MSDN: .NET 3.5+: IOException: The specified file is in use or there is an open handle on the file. NativeError.ThrowException(lastError, pathLp); break; case Win32Errors.ERROR_ACCESS_DENIED: var data = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA(); int dataInitialised = FillAttributeInfoCore(transaction, pathLp, ref data, false, true); if (data.dwFileAttributes != (FileAttributes)(-1)) { if ((data.dwFileAttributes & FileAttributes.Directory) != 0) { // MSDN: .NET 3.5+: UnauthorizedAccessException: Path is a directory. throw new UnauthorizedAccessException(string.Format(CultureInfo.CurrentCulture, "({0}) {1}", Win32Errors.ERROR_INVALID_PARAMETER, string.Format(CultureInfo.CurrentCulture, Resources.Target_File_Is_A_Directory, pathLp))); } if ((data.dwFileAttributes & FileAttributes.ReadOnly) != 0) { if (ignoreReadOnly) { // Reset file attributes. SetAttributesCore(false, transaction, pathLp, FileAttributes.Normal, true, PathFormat.LongFullPath); goto startDeleteFile; } // MSDN: .NET 3.5+: UnauthorizedAccessException: Path specified a read-only file. throw new FileReadOnlyException(pathLp); } } if (dataInitialised == Win32Errors.ERROR_SUCCESS) { // MSDN: .NET 3.5+: UnauthorizedAccessException: The caller does not have the required permission. NativeError.ThrowException(lastError, pathLp); } break; } // MSDN: .NET 3.5+: IOException: // The specified file is in use. // There is an open handle on the file, and the operating system is Windows XP or earlier. NativeError.ThrowException(lastError, pathLp); } }
internal static void DeleteFileInternal(KernelTransaction transaction, string path, bool ignoreReadOnly, PathFormat pathFormat) { #region Setup if (pathFormat == PathFormat.RelativePath) Path.CheckValidPath(path, true, true); string pathLp = Path.GetExtendedLengthPathInternal(transaction, path, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator); // If the path points to a symbolic link, the symbolic link is deleted, not the target. #endregion // Setup startDeleteFile: if (!(transaction == null || !NativeMethods.IsAtLeastWindowsVista // DeleteFile() / DeleteFileTransacted() // 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.DeleteFile(pathLp) : NativeMethods.DeleteFileTransacted(pathLp, transaction.SafeHandle))) { int lastError = Marshal.GetLastWin32Error(); switch ((uint)lastError) { case Win32Errors.ERROR_FILE_NOT_FOUND: // MSDN: .NET 3.5+: If the file to be deleted does not exist, no exception is thrown. return; case Win32Errors.ERROR_PATH_NOT_FOUND: // MSDN: .NET 3.5+: DirectoryNotFoundException: The specified path is invalid (for example, it is on an unmapped drive). NativeError.ThrowException(lastError, pathLp); return; case Win32Errors.ERROR_SHARING_VIOLATION: // MSDN: .NET 3.5+: IOException: The specified file is in use or there is an open handle on the file. NativeError.ThrowException(lastError, pathLp); break; case Win32Errors.ERROR_ACCESS_DENIED: var data = new NativeMethods.Win32FileAttributeData(); int dataInitialised = FillAttributeInfoInternal(transaction, pathLp, ref data, false, true); if (data.FileAttributes != (FileAttributes)(-1)) { if ((data.FileAttributes & FileAttributes.Directory) == FileAttributes.Directory) // MSDN: .NET 3.5+: UnauthorizedAccessException: Path is a directory. throw new UnauthorizedAccessException(string.Format(CultureInfo.CurrentCulture, "({0}) {1}", Win32Errors.ERROR_INVALID_PARAMETER, string.Format(CultureInfo.CurrentCulture, Resources.DirectoryExistsWithSameNameSpecifiedByPath, pathLp))); if ((data.FileAttributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { if (ignoreReadOnly) { // Reset file attributes. SetAttributesInternal(false, transaction, pathLp, FileAttributes.Normal, true, PathFormat.LongFullPath); goto startDeleteFile; } // MSDN: .NET 3.5+: UnauthorizedAccessException: Path specified a read-only file. throw new FileReadOnlyException(pathLp); } } if (dataInitialised == Win32Errors.ERROR_SUCCESS) // MSDN: .NET 3.5+: UnauthorizedAccessException: The caller does not have the required permission. NativeError.ThrowException(lastError, pathLp); break; } // MSDN: .NET 3.5+: IOException: // The specified file is in use. // There is an open handle on the file, and the operating system is Windows XP or earlier. NativeError.ThrowException(lastError, pathLp); } }
public static void Delete(string path, bool ignoreReadOnly, PathFormat pathFormat) { DeleteFileCore(null, path, ignoreReadOnly, pathFormat); }
public static void Delete(KernelTransaction transaction, string path, bool ignoreReadOnly, PathFormat pathFormat) { DeleteFileInternal(transaction, path, ignoreReadOnly, pathFormat); }
public static void DeleteEmptySubdirectories(string path, bool recursive, bool ignoreReadOnly, PathFormat pathFormat) { DeleteEmptySubdirectoriesCore(null, null, path, recursive, ignoreReadOnly, pathFormat); }