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);
                  }
               }
            }
         }
      }
Example #2
0
      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);
      }
Example #3
0
      private DirectoryInfo(KernelTransaction transaction, string fullPath, bool junk1, bool junk2)
      {
         IsDirectory = true;
         Transaction = transaction;

         LongFullName = Path.GetLongPathInternal(fullPath, GetFullPathOptions.None);

         OriginalPath = Path.GetFileName(fullPath, true);

         FullPath = fullPath;

         // GetDisplayName()
         DisplayPath = OriginalPath.Length != 2 || (OriginalPath[1] != Path.VolumeSeparatorChar) ? OriginalPath : Path.CurrentDirectoryPrefix;
      }
Example #4
0
 public static string[] GetDirectoriesTransacted(KernelTransaction transaction, string path, string searchPattern)
 {
     return(EnumerateFileSystemEntryInfosCore <string>(transaction, path, searchPattern, DirectoryEnumerationOptions.Folders, PathFormat.RelativePath).ToArray());
 }
Example #5
0
        public static IEnumerable <string> EnumerateFilesTransacted(KernelTransaction transaction, string path, string searchPattern, SearchOption searchOption, PathFormat pathFormat)
        {
            var options = DirectoryEnumerationOptions.Files | ((searchOption == SearchOption.AllDirectories) ? DirectoryEnumerationOptions.Recursive : 0);

            return(EnumerateFileSystemEntryInfosCore <string>(transaction, path, searchPattern, options, pathFormat));
        }
Example #6
0
      public static string GetDirectoryNameWithoutRoot(KernelTransaction transaction, string path)
      {
         if (path == null)
            return null;

         DirectoryInfo di = Directory.GetParentInternal(transaction, path, PathFormat.RelativePath);
         return di != null && di.Parent != null ? di.Name : null;
      }
 public static long CountFileSystemObjects(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationOptions options, PathFormat pathFormat)
 {
    return EnumerateFileSystemEntryInfosInternal<string>(transaction, path, searchPattern, options, pathFormat).Count();
 }
Example #8
0
 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;
    }
 }
Example #9
0
 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);
 }
Example #10
0
      internal static CopyMoveResult CopyMoveInternal(bool isFolder, KernelTransaction transaction, string sourceFileName, string destinationFileName, bool preserveDates, CopyOptions? copyOptions, MoveOptions? moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat)
      {
         #region Setup

         if (pathFormat == PathFormat.RelativePath)
         {
            Path.CheckValidPath(sourceFileName, true, true);
            Path.CheckValidPath(destinationFileName, true, true);
         }
         else
         {
            // MSDN:. NET 3.5+: NotSupportedException: Path contains a colon character (:) that is not part of a drive label ("C:\").
            Path.CheckValidPath(sourceFileName, false, false);
            Path.CheckValidPath(destinationFileName, false, false);
         }

         string sourceFileNameLp = Path.GetExtendedLengthPathInternal(transaction, sourceFileName, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator);
         string destFileNameLp = Path.GetExtendedLengthPathInternal(transaction, destinationFileName, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator);


         // MSDN: If this flag is set to TRUE during the copy/move operation, the operation is canceled.
         // Otherwise, the copy/move operation will continue to completion.
         bool cancel = false;

         // Determine Copy or Move action.
         bool doCopy = copyOptions != null;
         bool doMove = !doCopy && moveOptions != null;

         if ((!doCopy && !doMove) || (doCopy && doMove))
            throw new NotSupportedException(Resources.UndeterminedCopyMoveAction);

         bool overwrite = doCopy
            ? (((CopyOptions) copyOptions & CopyOptions.FailIfExists) != CopyOptions.FailIfExists)
            : (((MoveOptions) moveOptions & MoveOptions.ReplaceExisting) == MoveOptions.ReplaceExisting);

         bool raiseException = progressHandler == null;

         // Setup callback function for progress notifications.
         var routine = (progressHandler != null)
            ? (totalFileSize, totalBytesTransferred, streamSize, streamBytesTransferred, dwStreamNumber, dwCallbackReason, hSourceFile, hDestinationFile, lpData)
               =>
               progressHandler(totalFileSize, totalBytesTransferred, streamSize, streamBytesTransferred, dwStreamNumber, dwCallbackReason, userProgressData)
            : (NativeMethods.NativeCopyMoveProgressRoutine) null;

         #endregion //Setup

         startCopyMove:

         uint lastError = Win32Errors.ERROR_SUCCESS;

         #region Win32 Copy/Move

         if (!(transaction == null || !NativeMethods.IsAtLeastWindowsVista
            ? doMove
               // MoveFileWithProgress() / MoveFileTransacted()
               // 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-04-15: MSDN confirms LongPath usage.

               // CopyFileEx() / CopyFileTransacted()
               // 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-04-15: MSDN confirms LongPath usage.

               ? NativeMethods.MoveFileWithProgress(sourceFileNameLp, destFileNameLp, routine, IntPtr.Zero, (MoveOptions) moveOptions)
               : NativeMethods.CopyFileEx(sourceFileNameLp, destFileNameLp, routine, IntPtr.Zero, out cancel, (CopyOptions) copyOptions)

            : doMove
               ? NativeMethods.MoveFileTransacted(sourceFileNameLp, destFileNameLp, routine, IntPtr.Zero, (MoveOptions) moveOptions, transaction.SafeHandle)
               : NativeMethods.CopyFileTransacted(sourceFileNameLp, destFileNameLp, routine, IntPtr.Zero, out cancel, (CopyOptions) copyOptions, transaction.SafeHandle)))
         {
            lastError = (uint) Marshal.GetLastWin32Error();

            if (lastError == Win32Errors.ERROR_REQUEST_ABORTED)
            {
               // 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.

               cancel = true;
            }

            else if (raiseException)
            {
               #region Win32Errors

               switch (lastError)
               {
                  case Win32Errors.ERROR_FILE_NOT_FOUND:
                     // File.Copy()
                     // File.Move()
                     // MSDN: .NET 3.5+: FileNotFoundException: sourceFileName was not found. 
                     NativeError.ThrowException(lastError, sourceFileNameLp);
                     break;

                  case Win32Errors.ERROR_PATH_NOT_FOUND:
                     // File.Copy()
                     // File.Move()
                     // Directory.Move()
                     // MSDN: .NET 3.5+: DirectoryNotFoundException: The path specified in sourceFileName or destinationFileName is invalid (for example, it is on an unmapped drive).
                     NativeError.ThrowException(lastError, sourceFileNameLp);
                     break;

                  case Win32Errors.ERROR_FILE_EXISTS:
                     // File.Copy()
                     // Directory.Copy()
                     NativeError.ThrowException(lastError, destFileNameLp);
                     break;

                  default:
                     // For a number of error codes (sharing violation, path not found, etc)
                     // we don't know if the problem was with the source or dest file.

                     // Check if destination directory already exists.
                     // Directory.Move()
                     // MSDN: .NET 3.5+: IOException: destDirName already exists. 
                     if (ExistsInternal(true, transaction, destFileNameLp, PathFormat.LongFullPath))
                        NativeError.ThrowException(Win32Errors.ERROR_ALREADY_EXISTS, destFileNameLp);

                     if (doMove)
                     {
                        // Ensure that the source file or directory exists.
                        // Directory.Move()
                        // MSDN: .NET 3.5+: DirectoryNotFoundException: The path specified by sourceDirName is invalid (for example, it is on an unmapped drive). 
                        if (!ExistsInternal(isFolder, transaction, sourceFileNameLp, PathFormat.LongFullPath))
                           NativeError.ThrowException(isFolder ? Win32Errors.ERROR_PATH_NOT_FOUND : Win32Errors.ERROR_FILE_NOT_FOUND, sourceFileNameLp);
                     }


                     // Try reading the source file.
                     string fileNameLp = destFileNameLp;

                     if (!isFolder)
                     {
                        using (SafeFileHandle safeHandle = CreateFileInternal(transaction, sourceFileNameLp, ExtendedFileAttributes.None, null, FileMode.Open, 0, FileShare.Read, false, PathFormat.LongFullPath))
                           if (safeHandle.IsInvalid)
                              fileNameLp = sourceFileNameLp;
                     }

                     if (lastError == Win32Errors.ERROR_ACCESS_DENIED)
                     {
                        // File.Copy()
                        // File.Move()
                        // MSDN: .NET 3.5+: IOException: An I/O error has occurred.
                        //   Directory exists with the same name as the file.
                        if (!isFolder && ExistsInternal(true, transaction, destFileNameLp, PathFormat.LongFullPath))
                           NativeError.ThrowException(lastError, string.Format(CultureInfo.CurrentCulture, Resources.DirectoryExistsWithSameNameSpecifiedByPath, destFileNameLp));

                        else
                        {
                           var data = new NativeMethods.Win32FileAttributeData();
                           FillAttributeInfoInternal(transaction, destFileNameLp, ref data, false, true);

                           if (data.FileAttributes != (FileAttributes) (-1))
                           {
                              if ((data.FileAttributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                              {
                                 // MSDN: .NET 3.5+: IOException: The directory specified by path is read-only.

                                 if (overwrite)
                                 {
                                    // Reset file system object attributes.
                                    SetAttributesInternal(isFolder, transaction, destFileNameLp, FileAttributes.Normal, true, PathFormat.LongFullPath);
                                    goto startCopyMove;
                                 }

                                 // MSDN: .NET 3.5+: UnauthorizedAccessException: destinationFileName is read-only.
                                 // MSDN: Win32 CopyFileXxx: This function fails with ERROR_ACCESS_DENIED if the destination file already exists
                                 // and has the FILE_ATTRIBUTE_HIDDEN or FILE_ATTRIBUTE_READONLY attribute set.

                                 throw new FileReadOnlyException(destFileNameLp);
                              }

                              // MSDN: Win32 CopyFileXxx: This function fails with ERROR_ACCESS_DENIED if the destination file already exists
                              // and has the FILE_ATTRIBUTE_HIDDEN or FILE_ATTRIBUTE_READONLY attribute set.
                              if ((data.FileAttributes & FileAttributes.Hidden) == FileAttributes.Hidden)
                                 NativeError.ThrowException(lastError, string.Format(CultureInfo.CurrentCulture, Resources.FileHidden, destFileNameLp));
                           }

                           // Observation: .NET 3.5+: For files: UnauthorizedAccessException: The caller does not have the required permission.
                           // Observation: .NET 3.5+: For directories: IOException: The caller does not have the required permission.
                           NativeError.ThrowException(lastError, destFileNameLp);
                        }
                     }

                     // MSDN: .NET 3.5+: An I/O error has occurred. 
                     // File.Copy(): IOException: destinationFileName exists and overwrite is false.
                     // File.Move(): The destination file already exists or sourceFileName was not found.
                     NativeError.ThrowException(lastError, fileNameLp);
                     break;
               }

               #endregion // Win32Errors
            }
         }

         #endregion // Win32 Copy/Move

         #region Transfer Timestamps

         // Apply original Timestamps if requested.
         // MoveFileWithProgress() / MoveFileTransacted() automatically preserve Timestamps.
         // File.Copy()
         if (preserveDates && doCopy && lastError == Win32Errors.ERROR_SUCCESS)
         {
            // Currently preserveDates is only used with files.
            var data = new NativeMethods.Win32FileAttributeData();
            int dataInitialised = FillAttributeInfoInternal(transaction, sourceFileNameLp, ref data, false, true);

            if (dataInitialised == Win32Errors.ERROR_SUCCESS && data.FileAttributes != (FileAttributes) (-1))
               SetFsoDateTimeInternal(false, transaction, destFileNameLp, DateTime.FromFileTimeUtc(data.CreationTime),
                  DateTime.FromFileTimeUtc(data.LastAccessTime), DateTime.FromFileTimeUtc(data.LastWriteTime), PathFormat.LongFullPath);
         }

         #endregion // Transfer Timestamps

         // The copy/move operation succeeded, failed or was canceled.
         return new CopyMoveResult(sourceFileNameLp, destFileNameLp, isFolder, doMove, cancel, (int) lastError);
      }
 public static void DeleteEmptySubdirectoriesTransacted(KernelTransaction transaction, string path, bool recursive, bool ignoreReadOnly, PathFormat pathFormat)
 {
     DeleteEmptySubdirectoriesCore(null, transaction, path, recursive, ignoreReadOnly, true, pathFormat);
 }
Example #12
0
 public static void SetLastWriteTimeTransacted(KernelTransaction transaction, string path, DateTime lastWriteTime)
 {
     File.SetFsoDateTimeCore(transaction, path, null, null, lastWriteTime.ToUniversalTime(), false, PathFormat.RelativePath);
 }
Example #13
0
 public static void SetLastWriteTimeUtcTransacted(KernelTransaction transaction, string path, DateTime lastWriteTimeUtc, PathFormat pathFormat)
 {
     File.SetFsoDateTimeCore(transaction, path, null, null, lastWriteTimeUtc, false, pathFormat);
 }
Example #14
0
 public static void DeleteTransacted(KernelTransaction transaction, string path, bool ignoreReadOnly, PathFormat pathFormat)
 {
     DeleteFileCore(transaction, path, ignoreReadOnly, pathFormat);
 }
Example #15
0
 public static void DeleteTransacted(KernelTransaction transaction, string path)
 {
     DeleteFileCore(transaction, path, false, PathFormat.RelativePath);
 }
Example #16
0
        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) == 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.Target_File_Is_A_Directory, pathLp)));
                        }


                        if ((data.dwFileAttributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                        {
                            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);
            }
        }
Example #17
0
        public static string[] GetDirectoriesTransacted(KernelTransaction transaction, string path, string searchPattern, SearchOption searchOption)
        {
            var options = DirectoryEnumerationOptions.Folders | ((searchOption == SearchOption.AllDirectories) ? DirectoryEnumerationOptions.Recursive : 0);

            return(EnumerateFileSystemEntryInfosCore <string>(transaction, path, searchPattern, options, PathFormat.RelativePath).ToArray());
        }
Example #18
0
      internal static DateTime GetChangeTimeInternal(bool isFolder, KernelTransaction transaction, SafeFileHandle safeHandle, string path, bool getUtc, PathFormat pathFormat)
      {
         if (!NativeMethods.IsAtLeastWindowsVista)
            throw new PlatformNotSupportedException(Resources.RequiresWindowsVistaOrHigher);

         bool callerHandle = safeHandle != null;
         if (!callerHandle)
         {
            if (pathFormat != PathFormat.LongFullPath && Utils.IsNullOrWhiteSpace(path))
               throw new ArgumentNullException("path");

            string pathLp = Path.GetExtendedLengthPathInternal(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.CheckInvalidPathChars);

            safeHandle = CreateFileInternal(transaction, pathLp, isFolder ? ExtendedFileAttributes.BackupSemantics : ExtendedFileAttributes.Normal, null, FileMode.Open, FileSystemRights.ReadData, FileShare.ReadWrite, true, PathFormat.LongFullPath);
         }


         try
         {
            NativeMethods.IsValidHandle(safeHandle);
            
            using (var safeBuffer = new SafeGlobalMemoryBufferHandle(IntPtr.Size + Marshal.SizeOf(typeof(NativeMethods.FileBasicInfo))))
            {
               NativeMethods.FileBasicInfo fbi;

               if (!NativeMethods.GetFileInformationByHandleEx_FileBasicInfo(safeHandle, NativeMethods.FileInfoByHandleClass.FileBasicInfo, out fbi, (uint)safeBuffer.Capacity))
                  NativeError.ThrowException(Marshal.GetLastWin32Error());

               safeBuffer.StructureToPtr(fbi, true);
               NativeMethods.FileTime changeTime = safeBuffer.PtrToStructure<NativeMethods.FileBasicInfo>().ChangeTime;

               return getUtc
                  ? DateTime.FromFileTimeUtc(changeTime)
                  : DateTime.FromFileTime(changeTime);
            }
         }
         finally
         {
            // Handle is ours, dispose.
            if (!callerHandle && safeHandle != null)
               safeHandle.Close();
         }
      }
 public static LinkTargetInfo GetLinkTargetInfo(KernelTransaction transaction, string path)
 {
    return GetLinkTargetInfoInternal(transaction, path, PathFormat.RelativePath);
 }
        internal static void DeleteEmptySubdirectoriesCore(FileSystemEntryInfo fileSystemEntryInfo, KernelTransaction transaction, string path, bool recursive, bool ignoreReadOnly, bool initialize, PathFormat pathFormat)
        {
            #region Setup

            if (pathFormat == PathFormat.RelativePath)
            {
                Path.CheckSupportedPathFormat(path, true, true);
            }

            if (fileSystemEntryInfo == null)
            {
                if (!File.ExistsCore(true, transaction, path, pathFormat))
                {
                    NativeError.ThrowException(Win32Errors.ERROR_PATH_NOT_FOUND, path);
                }

                fileSystemEntryInfo = File.GetFileSystemEntryInfoCore(true, transaction, Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck), false, pathFormat);
            }

            if (fileSystemEntryInfo == null)
            {
                throw new ArgumentNullException("path");
            }

            string pathLp = fileSystemEntryInfo.LongFullPath;

            #endregion // Setup

            // Ensure path is a directory.
            if (!fileSystemEntryInfo.IsDirectory)
            {
                throw new IOException(string.Format(CultureInfo.CurrentCulture, Resources.Target_Directory_Is_A_File, pathLp));
            }


            var dirEnumOptions = DirectoryEnumerationOptions.Folders;

            if (recursive)
            {
                dirEnumOptions |= DirectoryEnumerationOptions.Recursive;
            }

            foreach (var fsei in EnumerateFileSystemEntryInfosCore <FileSystemEntryInfo>(transaction, pathLp, Path.WildcardStarMatchAll, dirEnumOptions, PathFormat.LongFullPath))
            {
                DeleteEmptySubdirectoriesCore(fsei, transaction, null, recursive, ignoreReadOnly, false, PathFormat.LongFullPath);
            }


            if (!EnumerateFileSystemEntryInfosCore <string>(transaction, pathLp, Path.WildcardStarMatchAll, DirectoryEnumerationOptions.FilesAndFolders, PathFormat.LongFullPath).Any())
            {
                // Prevent deleting path itself.
                if (!initialize)
                {
                    DeleteDirectoryCore(fileSystemEntryInfo, transaction, null, false, ignoreReadOnly, true, true, PathFormat.LongFullPath);
                }
            }
        }
Example #21
0
 public static void Copy(KernelTransaction transaction, string sourceFileName, string destinationFileName, CopyOptions copyOptions)
 {
    CopyMoveInternal(false, transaction, sourceFileName, destinationFileName, false, copyOptions, null, null, null, PathFormat.RelativePath);
 }
 public static void DeleteEmptySubdirectoriesTransacted(KernelTransaction transaction, string path, bool recursive)
 {
     DeleteEmptySubdirectoriesCore(null, transaction, path, recursive, false, true, PathFormat.RelativePath);
 }
Example #23
0
 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);
 }
 public static DateTime GetChangeTimeUtcTransacted(KernelTransaction transaction, string path, PathFormat pathFormat)
 {
     return(File.GetChangeTimeCore(transaction, null, path, true, pathFormat));
 }
Example #25
0
 public static string[] ReadAllLines(KernelTransaction transaction, string path, Encoding encoding)
 {
    return ReadAllLinesInternal(transaction, path, encoding, PathFormat.RelativePath).ToArray();
 }
 public static DateTime GetChangeTimeTransacted(KernelTransaction transaction, string path)
 {
     return(File.GetChangeTimeCore(transaction, null, path, false, PathFormat.RelativePath));
 }
Example #27
0
 public static string ReadAllText(KernelTransaction transaction, string path)
 {
    return ReadAllTextInternal(transaction, path, NativeMethods.DefaultFileEncoding, PathFormat.RelativePath);
 }
Example #28
0
 public static FileSystemEntryInfo GetFileSystemEntryInfoTransacted(KernelTransaction transaction, string path)
 {
     return(GetFileSystemEntryInfoCore(false, transaction, path, false, PathFormat.RelativePath));
 }
Example #29
0
 public static void Delete(KernelTransaction transaction, string path)
 {
    DeleteFileInternal(transaction, path, false, PathFormat.RelativePath);
 }
Example #30
0
      internal static long GetSizeInternal(KernelTransaction transaction, SafeFileHandle safeHandle, string path, PathFormat pathFormat)
      {
         bool callerHandle = safeHandle != null;
         if (!callerHandle)
         {
            string pathLp = Path.GetExtendedLengthPathInternal(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck);

            safeHandle = CreateFileInternal(transaction, pathLp, ExtendedFileAttributes.None, null, FileMode.Open, FileSystemRights.ReadData, FileShare.Read, true, PathFormat.LongFullPath);
         }


         long fileSize;

         try
         {
            NativeMethods.GetFileSizeEx(safeHandle, out fileSize);
         }
         finally
         {
            // Handle is ours, dispose.
            if (!callerHandle && safeHandle != null)
               safeHandle.Close();
         }

         return fileSize;
      }
Example #31
0
        internal static FileSystemEntryInfo GetFileSystemEntryInfoCore(bool isFolder, KernelTransaction transaction, string path, bool continueOnException, PathFormat pathFormat)
        {
            // Enable BasicSearch and LargeCache by default.
            var options = DirectoryEnumerationOptions.BasicSearch | DirectoryEnumerationOptions.LargeCache | (continueOnException ? DirectoryEnumerationOptions.ContinueOnException : 0);

            return((new FindFileSystemEntryInfo(isFolder, transaction, path, Path.WildcardStarMatchAll, options, typeof(FileSystemEntryInfo), pathFormat)).Get <FileSystemEntryInfo>());
        }
Example #32
0
 public static string[] GetDirectoriesTransacted(KernelTransaction transaction, string path)
 {
     return(EnumerateFileSystemEntryInfosCore <string>(transaction, path, Path.WildcardStarMatchAll, DirectoryEnumerationOptions.Folders, PathFormat.RelativePath).ToArray());
 }
Example #33
0
 public static long GetSize(KernelTransaction transaction, string path)
 {
    return GetSizeInternal(transaction, null, path, PathFormat.RelativePath);
 }
 public static DirectoryInfo GetParentTransacted(KernelTransaction transaction, string path, PathFormat pathFormat)
 {
     return(GetParentCore(transaction, path, pathFormat));
 }
Example #35
0
 public static DateTime GetChangeTimeUtc(KernelTransaction transaction, string path, PathFormat pathFormat)
 {
    return GetChangeTimeInternal(false, transaction, null, path, true, pathFormat);
 }
Example #36
0
 public static bool IsLockedTransacted(KernelTransaction transaction, string path, PathFormat pathFormat)
 {
     return(IsLockedCore(transaction, path, pathFormat));
 }
Example #37
0
 public static DateTime GetChangeTime(KernelTransaction transaction, string path)
 {
    return GetChangeTimeInternal(false, transaction, null, path, false, PathFormat.RelativePath);
 }
 public static void DecompressTransacted(KernelTransaction transaction, string path, PathFormat pathFormat)
 {
     Device.ToggleCompressionCore(transaction, path, false, pathFormat);
 }
 internal static LinkTargetInfo GetLinkTargetInfoInternal(KernelTransaction transaction, string path, PathFormat pathFormat)
 {
    using (SafeFileHandle safeHandle = CreateFileInternal(transaction, path, ExtendedFileAttributes.OpenReparsePoint | ExtendedFileAttributes.BackupSemantics, null, FileMode.Open, 0, FileShare.ReadWrite, true, pathFormat))
       return Device.GetLinkTargetInfoInternal(safeHandle);
 }
Example #40
0
 public BackupFileStream(KernelTransaction transaction, string path, FileMode mode)
     : this(transaction, path, mode, FileSystemRights.Read | FileSystemRights.Write)
 {
 }
Example #41
0
 public static void Copy(KernelTransaction transaction, string sourceFileName, string destinationFileName, bool overwrite, PathFormat pathFormat)
 {
    CopyMoveInternal(false, transaction, sourceFileName, destinationFileName, false, overwrite ? CopyOptions.None : CopyOptions.FailIfExists, null, null, null, pathFormat);
 }
Example #42
0
 public BackupFileStream(KernelTransaction transaction, string path, FileMode mode, FileSystemRights access, FileShare share, FileOptions options, FileSecurity security)
     : this(File.CreateInternal(transaction, path, mode, access, share, options, security), access)
 {
 }
Example #43
0
 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);
 }
Example #44
0
 public BackupFileStream(KernelTransaction transaction, string path, FileMode mode, FileSystemRights access, FileShare share)
     : this(transaction, path, mode, access, share, FileOptions.None)
 {
 }
Example #45
0
 public static void Move(KernelTransaction transaction, string sourceFileName, string destinationFileName)
 {
    CopyMoveInternal(false, transaction, sourceFileName, destinationFileName, false, null, MoveOptions.CopyAllowed, null, null, PathFormat.RelativePath);
 }
Example #46
0
 public static void SetCreationTimeUtcTransacted(KernelTransaction transaction, string path, DateTime creationTimeUtc, PathFormat pathFormat)
 {
     File.SetFsoDateTimeCore(transaction, path, creationTimeUtc, null, null, false, pathFormat);
 }
Example #47
0
 public static CopyMoveResult Move(KernelTransaction transaction, string sourceFileName, string destinationFileName, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData)
 {
    return CopyMoveInternal(false, transaction, sourceFileName, destinationFileName, false, null, moveOptions, progressHandler, userProgressData, PathFormat.RelativePath);
 }
Example #48
0
 public static void SetCreationTimeUtcTransacted(KernelTransaction transaction, string path, DateTime creationTimeUtc, bool modifyReparsePoint, PathFormat pathFormat)
 {
     File.SetFsoDateTimeCore(transaction, path, creationTimeUtc, null, null, modifyReparsePoint, pathFormat);
 }
Example #49
0
 public static string[] ReadAllLines(KernelTransaction transaction, string path)
 {
    return ReadAllLinesInternal(transaction, path, NativeMethods.DefaultFileEncoding, PathFormat.RelativePath).ToArray();
 }
Example #50
0
 /// <summary>[AlphaFS] Checks the specified <paramref name="path"/> for local or network drives, such as: "C:" and "\\server\c$".</summary>
 public static bool ExistsDrive(KernelTransaction transaction, string path, bool throwIfDriveNotExists)
 {
     return(ExistsDriveOrFolderOrFile(transaction, path, false, (int)Win32Errors.NO_ERROR, throwIfDriveNotExists, false));
 }
 public static long CountFileSystemObjects(KernelTransaction transaction, string path, DirectoryEnumerationOptions options, PathFormat pathFormat)
 {
    return EnumerateFileSystemEntryInfosInternal<string>(transaction, path, Path.WildcardStarMatchAll, options, pathFormat).Count();
 }
Example #52
0
 public static void SetTimestampsTransacted(KernelTransaction transaction, string path, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime, PathFormat pathFormat)
 {
     File.SetFsoDateTimeCore(transaction, path, creationTime.ToUniversalTime(), lastAccessTime.ToUniversalTime(), lastWriteTime.ToUniversalTime(), false, pathFormat);
 }
Example #53
0
 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();
 }
Example #54
0
 public static void SetTimestampsUtcTransacted(KernelTransaction transaction, string path, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc, PathFormat pathFormat)
 {
     File.SetFsoDateTimeCore(transaction, path, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc, false, pathFormat);
 }
Example #55
0
 public static string ReadAllText(KernelTransaction transaction, string path, Encoding encoding)
 {
    return ReadAllTextInternal(transaction, path, encoding, PathFormat.RelativePath);
 }
Example #56
0
 public static void SetTimestampsUtcTransacted(KernelTransaction transaction, string path, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc, bool modifyReparsePoint, PathFormat pathFormat)
 {
     File.SetFsoDateTimeCore(transaction, path, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc, modifyReparsePoint, pathFormat);
 }
Example #57
0
      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 SetCreationTimeTransacted(KernelTransaction transaction, string path, DateTime creationTime, PathFormat pathFormat)
 {
     File.SetFsoDateTimeCore(true, transaction, path, creationTime.ToUniversalTime(), null, null, false, pathFormat);
 }
Example #59
0
 public static void Delete(KernelTransaction transaction, string path, bool ignoreReadOnly, PathFormat pathFormat)
 {
    DeleteFileInternal(transaction, path, ignoreReadOnly, pathFormat);
 }
 public static void SetCreationTimeTransacted(KernelTransaction transaction, string path, DateTime creationTime, bool modifyReparsePoint, PathFormat pathFormat)
 {
     File.SetFsoDateTimeCore(true, transaction, path, creationTime.ToUniversalTime(), null, null, modifyReparsePoint, pathFormat);
 }