public static void Replace(String sourceFileName, String destinationFileName, String destinationBackupFileName, bool ignoreMetadataErrors) { if (sourceFileName == null) { throw new ArgumentNullException("sourceFileName"); } if (destinationFileName == null) { throw new ArgumentNullException("destinationFileName"); } String fullSrcPath = Path.NormalizeLongPath(Path.GetFullPath(sourceFileName)); String fullDestPath = Path.NormalizeLongPath(Path.GetFullPath(destinationFileName)); String fullBackupPath = null; if (destinationBackupFileName != null) { fullBackupPath = Path.NormalizeLongPath(Path.GetFullPath(destinationBackupFileName)); } int flags = NativeMethods.REPLACEFILE_WRITE_THROUGH; if (ignoreMetadataErrors) { flags |= NativeMethods.REPLACEFILE_IGNORE_MERGE_ERRORS; } bool r = NativeMethods.ReplaceFile(fullDestPath, fullSrcPath, fullBackupPath, flags, IntPtr.Zero, IntPtr.Zero); if (!r) { Common.ThrowIOError(Marshal.GetLastWin32Error(), String.Empty); } }
public void Refresh() { try { NativeMethods.WIN32_FIND_DATA findData; using (var handle = Directory.BeginFind(Path.NormalizeLongPath(FullPath), out findData)) { if (handle == null) { state = State.Error; errorCode = Marshal.GetLastWin32Error(); } else { data.From(findData); state = State.Initialized; } } } catch (DirectoryNotFoundException) { state = State.Error; errorCode = NativeMethods.ERROR_PATH_NOT_FOUND; } catch (Exception) { if (state != State.Error) { Common.ThrowIOError(Marshal.GetLastWin32Error(), string.Empty); } } }
public static void Encrypt(String path) { if (Common.IsRunningOnMono() && Common.IsPlatformUnix()) { SysFile.Encrypt(path); return; } String fullPath = Path.GetFullPath(path); string normalizedPath = Path.NormalizeLongPath(fullPath); if (NativeMethods.EncryptFile(normalizedPath)) { return; } int errorCode = Marshal.GetLastWin32Error(); if (errorCode == NativeMethods.ERROR_ACCESS_DENIED) { var di = new DriveInfo(Path.GetPathRoot(normalizedPath)); if (!String.Equals("NTFS", di.DriveFormat)) { throw new NotSupportedException("NTFS drive required for file encryption"); } } Common.ThrowIOError(errorCode, fullPath); }
public static DirectorySecurity GetAccessControl(string path, AccessControlSections includeSections) { var normalizedPath = Path.NormalizeLongPath(Path.GetFullPath(path)); IntPtr sidOwner, sidGroup, dacl, sacl, byteArray; var securityInfos = Common.ToSecurityInfos(includeSections); var errorCode = (int)NativeMethods.GetSecurityInfoByName(normalizedPath, (uint)ResourceType.FileObject, (uint)securityInfos, out sidOwner, out sidGroup, out dacl, out sacl, out byteArray); Common.ThrowIfError(errorCode, byteArray); var length = NativeMethods.GetSecurityDescriptorLength(byteArray); var binaryForm = new byte[length]; Marshal.Copy(byteArray, binaryForm, 0, (int)length); NativeMethods.LocalFree(byteArray); var ds = new DirectorySecurity(); ds.SetSecurityDescriptorBinaryForm(binaryForm); return(ds); }
internal static IEnumerable <string> EnumerateFileSystemEntries(string path, string searchPattern, bool includeDirectories, bool includeFiles, SearchOption option) { var normalizedSearchPattern = Common.NormalizeSearchPattern(searchPattern); var normalizedPath = Path.NormalizeLongPath(path); return(EnumerateNormalizedFileSystemEntries(includeDirectories, includeFiles, option, normalizedPath, normalizedSearchPattern)); }
public static FileSecurity GetAccessControl(string path, AccessControlSections includeSections) { var normalizedPath = Path.NormalizeLongPath(Path.GetFullPath(path)); IntPtr SidOwner, SidGroup, Dacl, Sacl, ByteArray; SecurityInfos SecurityInfos = Common.ToSecurityInfos(includeSections); int errorCode = (int)NativeMethods.GetSecurityInfoByName(normalizedPath, (uint)ResourceType.FileObject, (uint)SecurityInfos, out SidOwner, out SidGroup, out Dacl, out Sacl, out ByteArray); Common.ThrowIfError(errorCode, ByteArray); uint Length = NativeMethods.GetSecurityDescriptorLength(ByteArray); byte[] BinaryForm = new byte[Length]; Marshal.Copy(ByteArray, BinaryForm, 0, (int)Length); NativeMethods.LocalFree(ByteArray); var fs = new FileSecurity(); fs.SetSecurityDescriptorBinaryForm(BinaryForm); return(fs); }
public static string GetFileName(string path) { if (path == null) { return(null); } return(System.IO.Path.GetFileName(Path.NormalizeLongPath(path))); }
/// <summary> /// Deletes the specified empty directory. /// </summary> /// <param name="path"> /// A <see cref="string"/> containing the path of the directory to delete. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="path"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="path"/> is an empty string (""), contains only white /// space, or contains one or more invalid characters as defined in /// <see cref="Path.GetInvalidPathChars()"/>. /// <para> /// -or- /// </para> /// <paramref name="path"/> contains one or more components that exceed /// the drive-defined maximum length. For example, on Windows-based /// platforms, components must not exceed 255 characters. /// </exception> /// <exception cref="System.IO.PathTooLongException"> /// <paramref name="path"/> exceeds the system-defined maximum length. /// For example, on Windows-based platforms, paths must not exceed /// 32,000 characters. /// </exception> /// <exception cref="System.IO.DirectoryNotFoundException"> /// <paramref name="path"/> could not be found. /// </exception> /// <exception cref="UnauthorizedAccessException"> /// The caller does not have the required access permissions. /// <para> /// -or- /// </para> /// <paramref name="path"/> refers to a directory that is read-only. /// </exception> /// <exception cref="System.IO.IOException"> /// <paramref name="path"/> is a file. /// <para> /// -or- /// </para> /// <paramref name="path"/> refers to a directory that is not empty. /// <para> /// -or- /// </para> /// <paramref name="path"/> refers to a directory that is in use. /// <para> /// -or- /// </para> /// <paramref name="path"/> specifies a device that is not ready. /// </exception> public static void Delete(string path) { var normalizedPath = Path.NormalizeLongPath(path); if (!NativeMethods.RemoveDirectory(normalizedPath)) { throw Common.GetExceptionFromLastWin32Error(); } }
private static IEnumerable <string> EnumerateFileSystemIteratorRecursive(string normalizedPath, string normalizedSearchPattern, bool includeDirectories, bool includeFiles) { // NOTE: Any exceptions thrown from this method are thrown on a call to IEnumerator<string>.MoveNext() var pendingDirectories = new Queue <string>(); pendingDirectories.Enqueue(normalizedPath); while (pendingDirectories.Count > 0) { normalizedPath = pendingDirectories.Dequeue(); // get all subdirs to recurse in the next iteration foreach (var subdir in EnumerateNormalizedFileSystemEntries(true, false, SearchOption.TopDirectoryOnly, normalizedPath, "*")) { pendingDirectories.Enqueue(Path.NormalizeLongPath(subdir)); } var path = Common.IsPathUnc(normalizedPath) ? normalizedPath : Path.RemoveLongPathPrefix(normalizedPath); NativeMethods.WIN32_FIND_DATA findData; using (var handle = BeginFind(Path.Combine(normalizedPath, normalizedSearchPattern), out findData)) { if (handle == null) { continue; } do { var fullPath = Path.Combine(path, findData.cFileName); if (IsDirectory(findData.dwFileAttributes)) { if (IsCurrentOrParentDirectory(findData.cFileName)) { continue; } var fullNormalizedPath = Path.Combine(normalizedPath, findData.cFileName); System.Diagnostics.Debug.Assert(Exists(fullPath)); System.Diagnostics.Debug.Assert(Exists(Common.IsPathUnc(fullNormalizedPath) ? fullNormalizedPath : Path.RemoveLongPathPrefix(fullNormalizedPath))); if (includeDirectories) { yield return(Path.RemoveLongPathPrefix(fullPath)); } } else if (includeFiles) { yield return(Path.RemoveLongPathPrefix(fullPath)); } } while (NativeMethods.FindNextFile(handle, out findData)); var errorCode = Marshal.GetLastWin32Error(); if (errorCode != NativeMethods.ERROR_NO_MORE_FILES) { throw Common.GetExceptionFromWin32Error(errorCode); } } } }
internal static void SetAttributes(string path, FileAttributes fileAttributes) { string normalizedPath = Path.NormalizeLongPath(path); if (!NativeMethods.SetFileAttributes(normalizedPath, fileAttributes)) { throw GetExceptionFromLastWin32Error(); } }
internal static FileAttributes GetAttributes(string path, out int errorCode) { string normalizedPath = Path.NormalizeLongPath(path); FileAttributes fileAttributes = (FileAttributes)(NativeMethods.INVALID_FILE_ATTRIBUTES); errorCode = TryGetDirectoryAttributes(normalizedPath, out fileAttributes); return(fileAttributes); }
/// <summary> /// Deletes the specified file. /// </summary> /// <param name="path"> /// A <see cref="String"/> containing the path of the file to delete. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="path"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="path"/> is an empty string (""), contains only white /// space, or contains one or more invalid characters as defined in /// <see cref="Path.GetInvalidPathChars()"/>. /// <para> /// -or- /// </para> /// <paramref name="path"/> contains one or more components that exceed /// the drive-defined maximum length. For example, on Windows-based /// platforms, components must not exceed 255 characters. /// </exception> /// <exception cref="PathTooLongException"> /// <paramref name="path"/> exceeds the system-defined maximum length. /// For example, on Windows-based platforms, paths must not exceed /// 32,000 characters. /// </exception> /// <exception cref="FileNotFoundException"> /// <paramref name="path"/> could not be found. /// </exception> /// <exception cref="DirectoryNotFoundException"> /// One or more directories in <paramref name="path"/> could not be found. /// </exception> /// <exception cref="UnauthorizedAccessException"> /// The caller does not have the required access permissions. /// <para> /// -or- /// </para> /// <paramref name="path"/> refers to a file that is read-only. /// <para> /// -or- /// </para> /// <paramref name="path"/> is a directory. /// </exception> /// <exception cref="IOException"> /// <paramref name="path"/> refers to a file that is in use. /// <para> /// -or- /// </para> /// <paramref name="path"/> specifies a device that is not ready. /// </exception> public static void Delete(string path) { string normalizedPath = Path.NormalizeLongPath(path); if (!NativeMethods.DeleteFile(normalizedPath)) { throw Common.GetExceptionFromLastWin32Error(); } }
/// <summary> /// Creates the specified directory. /// </summary> /// <param name="path"> /// A <see cref="string"/> containing the path of the directory to create. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="path"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="path"/> is an empty string (""), contains only white /// space, or contains one or more invalid characters as defined in /// <see cref="Path.GetInvalidPathChars()"/>. /// <para> /// -or- /// </para> /// <paramref name="path"/> contains one or more components that exceed /// the drive-defined maximum length. For example, on Windows-based /// platforms, components must not exceed 255 characters. /// </exception> /// <exception cref="System.IO.PathTooLongException"> /// <paramref name="path"/> exceeds the system-defined maximum length. /// For example, on Windows-based platforms, paths must not exceed /// 32,000 characters. /// </exception> /// <exception cref="System.IO.DirectoryNotFoundException"> /// <paramref name="path"/> contains one or more directories that could not be /// found. /// </exception> /// <exception cref="UnauthorizedAccessException"> /// The caller does not have the required access permissions. /// </exception> /// <exception cref="System.IO.IOException"> /// <paramref name="path"/> is a file. /// <para> /// -or- /// </para> /// <paramref name="path"/> specifies a device that is not ready. /// </exception> /// <remarks> /// Note: Unlike <see cref="Directory.CreateDirectory(System.String)"/>, this method only creates /// the last directory in <paramref name="path"/>. /// </remarks> public static DirectoryInfo CreateDirectory(string path) { if (Common.IsPathUnc(path)) { return(CreateDirectoryUnc(path)); } var normalizedPath = Path.NormalizeLongPath(path); var fullPath = Path.RemoveLongPathPrefix(normalizedPath); var length = fullPath.Length; if (length >= 2 && Path.IsDirectorySeparator(fullPath[length - 1])) { --length; } var rootLength = Path.GetRootLength(fullPath); var pathComponents = new List <string>(); if (length > rootLength) { for (var index = length - 1; index >= rootLength; --index) { var subPath = fullPath.Substring(0, index + 1); if (!Exists(subPath)) { pathComponents.Add(Path.NormalizeLongPath(subPath)); } while (index > rootLength && fullPath[index] != System.IO.Path.DirectorySeparatorChar && fullPath[index] != System.IO.Path.AltDirectorySeparatorChar) { --index; } } } while (pathComponents.Count > 0) { var str = pathComponents[pathComponents.Count - 1]; pathComponents.RemoveAt(pathComponents.Count - 1); if (NativeMethods.CreateDirectory(str, IntPtr.Zero)) { continue; } // To mimic Directory.CreateDirectory, we don't throw if the directory (not a file) already exists var errorCode = Marshal.GetLastWin32Error(); // PR: Not sure this is even possible, we check for existance above. //if (errorCode != NativeMethods.ERROR_ALREADY_EXISTS || !Exists(path)) //{ throw Common.GetExceptionFromWin32Error(errorCode); //} } return(new DirectoryInfo(fullPath)); }
/// <summary> /// Moves the specified file to a new location. /// </summary> /// <param name="sourcePath"> /// A <see cref="String"/> containing the path of the file to move. /// </param> /// <param name="destinationPath"> /// A <see cref="String"/> containing the new path of the file. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="sourcePath"/> and/or <paramref name="destinationPath"/> is /// <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="sourcePath"/> and/or <paramref name="destinationPath"/> is /// an empty string (""), contains only white space, or contains one or more /// invalid characters as defined in <see cref="Path.GetInvalidPathChars()"/>. /// <para> /// -or- /// </para> /// <paramref name="sourcePath"/> and/or <paramref name="destinationPath"/> /// contains one or more components that exceed the drive-defined maximum length. /// For example, on Windows-based platforms, components must not exceed 255 characters. /// </exception> /// <exception cref="PathTooLongException"> /// <paramref name="sourcePath"/> and/or <paramref name="destinationPath"/> /// exceeds the system-defined maximum length. For example, on Windows-based platforms, /// paths must not exceed 32,000 characters. /// </exception> /// <exception cref="FileNotFoundException"> /// <paramref name="sourcePath"/> could not be found. /// </exception> /// <exception cref="DirectoryNotFoundException"> /// One or more directories in <paramref name="sourcePath"/> and/or /// <paramref name="destinationPath"/> could not be found. /// </exception> /// <exception cref="UnauthorizedAccessException"> /// The caller does not have the required access permissions. /// </exception> /// <exception cref="IOException"> /// <paramref name="destinationPath"/> refers to a file that already exists. /// <para> /// -or- /// </para> /// <paramref name="sourcePath"/> and/or <paramref name="destinationPath"/> is a /// directory. /// <para> /// -or- /// </para> /// <paramref name="sourcePath"/> refers to a file that is in use. /// <para> /// -or- /// </para> /// <paramref name="sourcePath"/> and/or <paramref name="destinationPath"/> specifies /// a device that is not ready. /// </exception> public static void Move(string sourcePath, string destinationPath) { string normalizedSourcePath = Path.NormalizeLongPath(sourcePath, "sourcePath"); string normalizedDestinationPath = Path.NormalizeLongPath(destinationPath, "destinationPath"); if (!NativeMethods.MoveFile(normalizedSourcePath, normalizedDestinationPath)) { throw Common.GetExceptionFromLastWin32Error(); } }
internal virtual string GetNormalizedPathWithSearchPattern() { // https://docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-findfirstfilew // "If the string ends with a wildcard, period (.), or directory name, the user must have access permissions to the root and all subdirectories on the path" // This is a problem if the executing principal has no access to the parent folder; // appending "\*" fixes this while still allowing retrieval of attributes if (this is DirectoryInfo) { return(Path.NormalizeLongPath(Path.Combine(FullPath, "*"))); } return(Path.NormalizeLongPath(FullPath)); }
public static void SetAccessControl(string path, DirectorySecurity directorySecurity) { if (path == null) { throw new ArgumentNullException("path"); } if (directorySecurity == null) { throw new ArgumentNullException("directorySecurity"); } var name = Path.NormalizeLongPath(Path.GetFullPath(path)); Common.SetAccessControlExtracted(directorySecurity, name); }
internal static FileAttributes GetFileAttributes(string path) { string normalizedPath = Path.NormalizeLongPath(path); FileAttributes fileAttributes; int errorCode = TryGetFileAttributes(normalizedPath, out fileAttributes); if (errorCode != NativeMethods.ERROR_SUCCESS) { throw GetExceptionFromWin32Error(errorCode); } return(fileAttributes); }
/// <summary> /// Copies the specified file to a specified new file, indicating whether to overwrite an existing file. /// </summary> /// <param name="sourcePath"> /// A <see cref="String"/> containing the path of the file to copy. /// </param> /// <param name="destinationPath"> /// A <see cref="String"/> containing the new path of the file. /// </param> /// <param name="overwrite"> /// <see langword="true"/> if <paramref name="destinationPath"/> should be overwritten /// if it refers to an existing file, otherwise, <see langword="false"/>. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="sourcePath"/> and/or <paramref name="destinationPath"/> is /// <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="sourcePath"/> and/or <paramref name="destinationPath"/> is /// an empty string (""), contains only white space, or contains one or more /// invalid characters as defined in <see cref="Path.GetInvalidPathChars()"/>. /// <para> /// -or- /// </para> /// <paramref name="sourcePath"/> and/or <paramref name="destinationPath"/> /// contains one or more components that exceed the drive-defined maximum length. /// For example, on Windows-based platforms, components must not exceed 255 characters. /// </exception> /// <exception cref="PathTooLongException"> /// <paramref name="sourcePath"/> and/or <paramref name="destinationPath"/> /// exceeds the system-defined maximum length. For example, on Windows-based platforms, /// paths must not exceed 32,000 characters. /// </exception> /// <exception cref="FileNotFoundException"> /// <paramref name="sourcePath"/> could not be found. /// </exception> /// <exception cref="DirectoryNotFoundException"> /// One or more directories in <paramref name="sourcePath"/> and/or /// <paramref name="destinationPath"/> could not be found. /// </exception> /// <exception cref="UnauthorizedAccessException"> /// The caller does not have the required access permissions. /// <para> /// -or- /// </para> /// <paramref name="overwrite"/> is true and <paramref name="destinationPath"/> refers to a /// file that is read-only. /// </exception> /// <exception cref="IOException"> /// <paramref name="overwrite"/> is false and <paramref name="destinationPath"/> refers to /// a file that already exists. /// <para> /// -or- /// </para> /// <paramref name="sourcePath"/> and/or <paramref name="destinationPath"/> is a /// directory. /// <para> /// -or- /// </para> /// <paramref name="overwrite"/> is true and <paramref name="destinationPath"/> refers to /// a file that already exists and is in use. /// <para> /// -or- /// </para> /// <paramref name="sourcePath"/> refers to a file that is in use. /// <para> /// -or- /// </para> /// <paramref name="sourcePath"/> and/or <paramref name="destinationPath"/> specifies /// a device that is not ready. /// </exception> public static void Copy(string sourcePath, string destinationPath, bool overwrite) { if (Common.IsRunningOnMono() && Common.IsPlatformUnix()) { SysFile.Copy(sourcePath, destinationPath, overwrite); } string normalizedSourcePath = Path.NormalizeLongPath(sourcePath, "sourcePath"); string normalizedDestinationPath = Path.NormalizeLongPath(destinationPath, "destinationPath"); if (!NativeMethods.CopyFile(normalizedSourcePath, normalizedDestinationPath, !overwrite)) { throw Common.GetExceptionFromLastWin32Error(); } }
/// <summary> /// Deletes the specified file. /// </summary> /// <param name="path"> /// A <see cref="String"/> containing the path of the file to delete. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="path"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="path"/> is an empty string (""), contains only white /// space, or contains one or more invalid characters as defined in /// <see cref="Path.GetInvalidPathChars()"/>. /// <para> /// -or- /// </para> /// <paramref name="path"/> contains one or more components that exceed /// the drive-defined maximum length. For example, on Windows-based /// platforms, components must not exceed 255 characters. /// </exception> /// <exception cref="PathTooLongException"> /// <paramref name="path"/> exceeds the system-defined maximum length. /// For example, on Windows-based platforms, paths must not exceed /// 32,000 characters. /// </exception> /// <exception cref="FileNotFoundException"> /// <paramref name="path"/> could not be found. /// </exception> /// <exception cref="DirectoryNotFoundException"> /// One or more directories in <paramref name="path"/> could not be found. /// </exception> /// <exception cref="UnauthorizedAccessException"> /// The caller does not have the required access permissions. /// <para> /// -or- /// </para> /// <paramref name="path"/> refers to a file that is read-only. /// <para> /// -or- /// </para> /// <paramref name="path"/> is a directory. /// </exception> /// <exception cref="IOException"> /// <paramref name="path"/> refers to a file that is in use. /// <para> /// -or- /// </para> /// <paramref name="path"/> specifies a device that is not ready. /// </exception> public static void Delete(string path) { if (Common.IsRunningOnMono() && Common.IsPlatformUnix()) { SysFile.Delete(path); return; } string normalizedPath = Path.NormalizeLongPath(path); if (!NativeMethods.DeleteFile(normalizedPath)) { throw Common.GetExceptionFromLastWin32Error(); } }
private static DirectoryInfo CreateDirectoryUnc(string path) { var length = path.Length; if (length >= 2 && Path.IsDirectorySeparator(path[length - 1])) { --length; } var rootLength = Path.GetRootLength(path); var pathComponents = new List <string>(); if (length > rootLength) { for (var index = length - 1; index >= rootLength; --index) { var subPath = path.Substring(0, index + 1); if (!Exists(subPath)) { pathComponents.Add(subPath); } while (index > rootLength && path[index] != System.IO.Path.DirectorySeparatorChar && path[index] != System.IO.Path.AltDirectorySeparatorChar) { --index; } } } while (pathComponents.Count > 0) { var str = Path.NormalizeLongPath(pathComponents[pathComponents.Count - 1]); pathComponents.RemoveAt(pathComponents.Count - 1); if (NativeMethods.CreateDirectory(str, IntPtr.Zero)) { continue; } // To mimic Directory.CreateDirectory, we don't throw if the directory (not a file) already exists var errorCode = Marshal.GetLastWin32Error(); if (errorCode != NativeMethods.ERROR_ALREADY_EXISTS || !Exists(path)) { throw Common.GetExceptionFromWin32Error(errorCode); } } return(new DirectoryInfo(path)); }
/// <summary> /// Opens the specified file. /// </summary> /// <param name="path"> /// A <see cref="String"/> containing the path of the file to open. /// </param> /// <param name="access"> /// One of the <see cref="FileAccess"/> value that specifies the operations that can be /// performed on the file. /// </param> /// <param name="mode"> /// One of the <see cref="FileMode"/> values that specifies whether a file is created /// if one does not exist, and determines whether the contents of existing files are /// retained or overwritten. /// </param> /// <param name="share"> /// One of the <see cref="FileShare"/> values specifying the type of access other threads /// have to the file. /// </param> /// <param name="bufferSize"> /// An <see cref="Int32"/> containing the number of bytes to buffer for reads and writes /// to the file, or 0 to specified the default buffer size, 1024. /// </param> /// <param name="options"> /// One or more of the <see cref="FileOptions"/> values that describes how to create or /// overwrite the file. /// </param> /// <returns> /// A <see cref="FileStream"/> that provides access to the file specified in /// <paramref name="path"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="path"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="path"/> is an empty string (""), contains only white /// space, or contains one or more invalid characters as defined in /// <see cref="Path.GetInvalidPathChars()"/>. /// <para> /// -or- /// </para> /// <paramref name="path"/> contains one or more components that exceed /// the drive-defined maximum length. For example, on Windows-based /// platforms, components must not exceed 255 characters. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="bufferSize"/> is less than 0. /// </exception> /// <exception cref="PathTooLongException"> /// <paramref name="path"/> exceeds the system-defined maximum length. /// For example, on Windows-based platforms, paths must not exceed /// 32,000 characters. /// </exception> /// <exception cref="DirectoryNotFoundException"> /// One or more directories in <paramref name="path"/> could not be found. /// </exception> /// <exception cref="UnauthorizedAccessException"> /// The caller does not have the required access permissions. /// <para> /// -or- /// </para> /// <paramref name="path"/> refers to a file that is read-only and <paramref name="access"/> /// is not <see cref="FileAccess.Read"/>. /// <para> /// -or- /// </para> /// <paramref name="path"/> is a directory. /// </exception> /// <exception cref="IOException"> /// <paramref name="path"/> refers to a file that is in use. /// <para> /// -or- /// </para> /// <paramref name="path"/> specifies a device that is not ready. /// </exception> internal static FileStream Open(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options) { const int defaultBufferSize = 1024; if (bufferSize == 0) { bufferSize = defaultBufferSize; } string normalizedPath = Path.NormalizeLongPath(path); SafeFileHandle handle = GetFileHandle(normalizedPath, mode, access, share, options); return(new FileStream(handle, access, bufferSize, (options & FileOptions.Asynchronous) == FileOptions.Asynchronous)); }
public static unsafe void SetLastAccessTimeUtc(String path, DateTime lastAccessTimeUtc) { string normalizedPath = Path.NormalizeLongPath(path); using (SafeFileHandle handle = GetFileHandle(normalizedPath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite, FileOptions.None)) { var fileTime = new NativeMethods.FILE_TIME(lastAccessTimeUtc.ToFileTimeUtc()); bool r = NativeMethods.SetFileTime(handle, null, &fileTime, null); if (!r) { int errorCode = Marshal.GetLastWin32Error(); Common.ThrowIOError(errorCode, path); } } }
/// <summary> /// Moves the specified file to a new location. /// </summary> /// <param name="sourcePath"> /// A <see cref="String"/> containing the path of the file to move. /// </param> /// <param name="destinationPath"> /// A <see cref="String"/> containing the new path of the file. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="sourcePath"/> and/or <paramref name="destinationPath"/> is /// <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="sourcePath"/> and/or <paramref name="destinationPath"/> is /// an empty string (""), contains only white space, or contains one or more /// invalid characters as defined in <see cref="Path.GetInvalidPathChars()"/>. /// <para> /// -or- /// </para> /// <paramref name="sourcePath"/> and/or <paramref name="destinationPath"/> /// contains one or more components that exceed the drive-defined maximum length. /// For example, on Windows-based platforms, components must not exceed 255 characters. /// </exception> /// <exception cref="PathTooLongException"> /// <paramref name="sourcePath"/> and/or <paramref name="destinationPath"/> /// exceeds the system-defined maximum length. For example, on Windows-based platforms, /// paths must not exceed 32,000 characters. /// </exception> /// <exception cref="FileNotFoundException"> /// <paramref name="sourcePath"/> could not be found. /// </exception> /// <exception cref="DirectoryNotFoundException"> /// One or more directories in <paramref name="sourcePath"/> and/or /// <paramref name="destinationPath"/> could not be found. /// </exception> /// <exception cref="UnauthorizedAccessException"> /// The caller does not have the required access permissions. /// </exception> /// <exception cref="IOException"> /// <paramref name="destinationPath"/> refers to a file that already exists. /// <para> /// -or- /// </para> /// <paramref name="sourcePath"/> and/or <paramref name="destinationPath"/> is a /// directory. /// <para> /// -or- /// </para> /// <paramref name="sourcePath"/> refers to a file that is in use. /// <para> /// -or- /// </para> /// <paramref name="sourcePath"/> and/or <paramref name="destinationPath"/> specifies /// a device that is not ready. /// </exception> public static void Move(string sourcePath, string destinationPath) { if (Common.IsRunningOnMono() && Common.IsPlatformUnix()) { SysFile.Move(sourcePath, destinationPath); return; } string normalizedSourcePath = Path.NormalizeLongPath(sourcePath, "sourcePath"); string normalizedDestinationPath = Path.NormalizeLongPath(destinationPath, "destinationPath"); if (!NativeMethods.MoveFile(normalizedSourcePath, normalizedDestinationPath)) { throw Common.GetExceptionFromLastWin32Error(); } }
public static string GetPathRoot(string path) { if (path == null) { return(null); } if (Path.IsPathRooted(path)) { if (!Common.IsPathUnc(path)) { path = Path.RemoveLongPathPrefix(Path.NormalizeLongPath(path)); } return(path.Substring(0, GetRootLength(path))); } return(string.Empty); }
public static unsafe void SetLastAccessTimeUtc(string path, DateTime lastWriteTimeUtc) { var normalizedPath = Path.NormalizeLongPath(Path.GetFullPath(path)); using (var handle = GetDirectoryHandle(normalizedPath)) { var fileTime = new NativeMethods.FILE_TIME(lastWriteTimeUtc.ToFileTimeUtc()); var r = NativeMethods.SetFileTime(handle, null, &fileTime, null); if (r) { return; } var errorCode = Marshal.GetLastWin32Error(); Common.ThrowIOError(errorCode, path); } }
public static void SetCurrentDirectory(string path) { #if true throw new NotSupportedException("Windows does not support setting the current directory to a long path"); #else string normalizedPath = Path.NormalizeLongPath(Path.GetFullPath(path)); if (!NativeMethods.SetCurrentDirectory(normalizedPath)) { int lastWin32Error = Marshal.GetLastWin32Error(); if (lastWin32Error == NativeMethods.ERROR_FILE_NOT_FOUND) { lastWin32Error = NativeMethods.ERROR_PATH_NOT_FOUND; } Common.ThrowIOError(lastWin32Error, normalizedPath); } #endif }
public static void Move(string sourcePath, string destinationPath) { string normalizedSourcePath = Path.NormalizeLongPath(sourcePath, "sourcePath"); string normalizedDestinationPath = Path.NormalizeLongPath(destinationPath, "destinationPath"); if (NativeMethods.MoveFile(normalizedSourcePath, normalizedDestinationPath)) { return; } var lastWin32Error = Marshal.GetLastWin32Error(); if (lastWin32Error == NativeMethods.ERROR_ACCESS_DENIED) { throw new System.IO.IOException(string.Format("Access to the path '{0}'is denied.", sourcePath), NativeMethods.MakeHRFromErrorCode(lastWin32Error)); } throw Common.GetExceptionFromWin32Error(lastWin32Error, "path"); }
/// <include path='doc/members/member[@name="M:System.IO.Path.GetDirectoryName(System.String)"]/*' file='..\ref\mscorlib.xml' /> public static string GetDirectoryName(string path) { if (Common.IsRunningOnMono() && Common.IsPlatformUnix()) { return(System.IO.Path.GetDirectoryName(path)); } if (path == null) { throw new ArgumentNullException("path"); } Path.CheckInvalidPathChars(path); string basePath = null; if (!IsPathRooted(path)) { basePath = System.IO.Directory.GetCurrentDirectory(); } path = Path.RemoveLongPathPrefix(Path.NormalizeLongPath(path)); int rootLength = GetRootLength(path); if (path.Length <= rootLength) { return(null); } int length = path.Length; do { } while (length > rootLength && path[--length] != System.IO.Path.DirectorySeparatorChar && path[length] != System.IO.Path.AltDirectorySeparatorChar); if (basePath != null) { path = path.Substring(basePath.Length + 1); length = length - basePath.Length - 1; if (length < 0) { length = 0; } } return(path.Substring(0, length)); }
public static void SetAccessControl(string path, FileSecurity fileSecurity) { if (Common.IsRunningOnMono() && Common.IsPlatformUnix()) { SysFile.SetAccessControl(path, fileSecurity); return; } if (path == null) { throw new ArgumentNullException("path"); } if (fileSecurity == null) { throw new ArgumentNullException("fileSecurity"); } var name = Path.NormalizeLongPath(Path.GetFullPath(path)); Common.SetAccessControlExtracted(fileSecurity, name); }
public static unsafe void SetCreationTimeUtc(String path, DateTime creationTimeUtc) { if (Common.IsRunningOnMono() && Common.IsPlatformUnix()) { SysFile.SetCreationTimeUtc(path, creationTimeUtc); return; } string normalizedPath = Path.NormalizeLongPath(path); using (SafeFileHandle handle = GetFileHandle(normalizedPath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite, FileOptions.None)) { var fileTime = new NativeMethods.FILE_TIME(creationTimeUtc.ToFileTimeUtc()); bool r = NativeMethods.SetFileTime(handle, &fileTime, null, null); if (!r) { int errorCode = Marshal.GetLastWin32Error(); Common.ThrowIOError(errorCode, path); } } }