private static void InternalMove(String sourceFileName, String destFileName) { if (sourceFileName == null) { throw new ArgumentNullException(nameof(sourceFileName), Environment.GetResourceString("ArgumentNull_FileName")); } if (destFileName == null) { throw new ArgumentNullException(nameof(destFileName), Environment.GetResourceString("ArgumentNull_FileName")); } if (sourceFileName.Length == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(sourceFileName)); } if (destFileName.Length == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(destFileName)); } Contract.EndContractBlock(); String fullSourceFileName = Path.GetFullPath(sourceFileName); String fullDestFileName = Path.GetFullPath(destFileName); if (!InternalExists(fullSourceFileName)) { __Error.WinIOError(Win32Native.ERROR_FILE_NOT_FOUND, fullSourceFileName); } if (!Win32Native.MoveFile(fullSourceFileName, fullDestFileName)) { __Error.WinIOError(); } }
/// <devdoc> /// Note: This returns the fully qualified name of the destination file. /// </devdoc> internal static String InternalCopy(String sourceFileName, String destFileName, bool overwrite) { Contract.Requires(sourceFileName != null); Contract.Requires(destFileName != null); Contract.Requires(sourceFileName.Length > 0); Contract.Requires(destFileName.Length > 0); String fullSourceFileName = Path.GetFullPath(sourceFileName); String fullDestFileName = Path.GetFullPath(destFileName); bool r = Win32Native.CopyFile(fullSourceFileName, fullDestFileName, !overwrite); if (!r) { // Save Win32 error because subsequent checks will overwrite this HRESULT. int errorCode = Marshal.GetLastWin32Error(); String fileName = destFileName; if (errorCode != Win32Native.ERROR_FILE_EXISTS) { if (errorCode == Win32Native.ERROR_ACCESS_DENIED) { if (Directory.InternalExists(fullDestFileName)) { throw new IOException(Environment.GetResourceString("Arg_FileIsDirectory_Name", destFileName), Win32Native.ERROR_ACCESS_DENIED, fullDestFileName); } } } __Error.WinIOError(errorCode, fileName); } return(fullDestFileName); }
public void MoveTo(String destFileName) { if (destFileName == null) { throw new ArgumentNullException("destFileName"); } if (destFileName.Length == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName"); } Contract.EndContractBlock(); String fullDestFileName = Path.GetFullPathInternal(destFileName); #if FEATURE_CORECLR FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Write | FileSecurityStateAccess.Read, DisplayPath, FullPath); FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destFileName, fullDestFileName); sourceState.EnsureState(); destState.EnsureState(); #else new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, new String[] { FullPath }, false, false).Demand(); FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullDestFileName, false, false); #endif if (!Win32Native.MoveFile(FullPath, fullDestFileName)) { __Error.WinIOError(); } FullPath = fullDestFileName; OriginalPath = destFileName; _name = Path.GetFileName(fullDestFileName); DisplayPath = GetDisplayPath(destFileName); // Flush any cached information about the file. _dataInitialised = -1; }
internal static void InternalDelete(String path, bool checkHost) { String fullPath = Path.GetFullPath(path); if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, path, fullPath); state.EnsureState(); } bool r = Win32Native.DeleteFile(fullPath); if (!r) { int hr = Marshal.GetLastWin32Error(); if (hr == Win32Native.ERROR_FILE_NOT_FOUND) { return; } else { __Error.WinIOError(hr, fullPath); } } }
public static void Encrypt(String path) { if (path == null) { throw new ArgumentNullException(nameof(path)); } Contract.EndContractBlock(); String fullPath = Path.GetFullPath(path); FileIOPermission.QuickDemand(FileIOPermissionAccess.Read | FileIOPermissionAccess.Write, fullPath, false, false); bool r = Win32Native.EncryptFile(fullPath); if (!r) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Win32Native.ERROR_ACCESS_DENIED) { // Check to see if the file system is not NTFS. If so, // throw a different exception. DriveInfo di = new DriveInfo(Path.GetPathRoot(fullPath)); if (!String.Equals("NTFS", di.DriveFormat)) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_EncryptionNeedsNTFS")); } } __Error.WinIOError(errorCode, fullPath); } }
// Deletes a file. The file specified by the designated path is deleted. // If the file does not exist, Delete succeeds without throwing // an exception. // // On NT, Delete will fail for a file that is open for normal I/O // or a file that is memory mapped. On Win95, the file will be // deleted irregardless of whether the file is being used. // // Your application must have Delete permission to the target file. // /// <include file='doc\FileInfo.uex' path='docs/doc[@for="FileInfo.Delete"]/*' /> public override void Delete() { // For security check, path should be resolved to an absolute path. new FileIOPermission(FileIOPermissionAccess.Write, new String[] { FullPath }, false, false).Demand(); if (System.IO.Directory.InternalExists(FullPath)) // Win9x hack to behave same as Winnt. Win9x fails silently for directories { throw new UnauthorizedAccessException(String.Format(Environment.GetResourceString("UnauthorizedAccess_IODenied_Path"), OriginalPath)); } bool r = Win32Native.DeleteFile(FullPath); if (!r) { int hr = Marshal.GetLastWin32Error(); if (hr == Win32Native.ERROR_FILE_NOT_FOUND) { return; } else { __Error.WinIOError(hr, OriginalPath); } } }
internal static void Delete(String path) { Contract.Requires(path != null); String fullPath = LongPath.NormalizePath(path); // For security check, path should be resolved to an absolute path. new FileIOPermission(FileIOPermissionAccess.Write, new String[] { fullPath }, false, false).Demand(); String tempPath = Path.AddLongPathPrefix(fullPath); bool r = Win32Native.DeleteFile(tempPath); if (!r) { int hr = Marshal.GetLastWin32Error(); if (hr == Win32Native.ERROR_FILE_NOT_FOUND) { return; } else { __Error.WinIOError(hr, fullPath); } } }
public static String PtrToStringAnsi(IntPtr ptr) { if (Win32Native.NULL == ptr) { return(null); } else if (IsWin32Atom(ptr)) { return(null); } else { int nb = Win32Native.lstrlenA(ptr); if (nb == 0) { return(string.Empty); } else { StringBuilder sb = new StringBuilder(nb); Win32Native.CopyMemoryAnsi(sb, ptr, new IntPtr(1 + nb)); return(sb.ToString()); } } }
internal static void Move(String sourceFileName, String destFileName) { Contract.Requires(sourceFileName != null); Contract.Requires(destFileName != null); Contract.Requires(sourceFileName.Length > 0); Contract.Requires(destFileName.Length > 0); String fullSourceFileName = LongPath.NormalizePath(sourceFileName); new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, new String[] { fullSourceFileName }, false, false).Demand(); String fullDestFileName = LongPath.NormalizePath(destFileName); new FileIOPermission(FileIOPermissionAccess.Write, new String[] { fullDestFileName }, false, false).Demand(); if (!LongPathFile.InternalExists(fullSourceFileName)) { __Error.WinIOError(Win32Native.ERROR_FILE_NOT_FOUND, fullSourceFileName); } String tempSourceFileName = Path.AddLongPathPrefix(fullSourceFileName); String tempDestFileName = Path.AddLongPathPrefix(fullDestFileName); if (!Win32Native.MoveFile(tempSourceFileName, tempDestFileName)) { __Error.WinIOError(); } }
// Deletes a file. The file specified by the designated path is deleted. // If the file does not exist, Delete succeeds without throwing // an exception. // // On NT, Delete will fail for a file that is open for normal I/O // or a file that is memory mapped. On Win95, the file will be // deleted irregardless of whether the file is being used. // // Your application must have Delete permission to the target file. // /// <include file='doc\File.uex' path='docs/doc[@for="File.Delete"]/*' /> public static void Delete(String path) { if (path == null) { throw new ArgumentNullException("path"); } String fullPath = Path.GetFullPathInternal(path); // For security check, path should be resolved to an absolute path. new FileIOPermission(FileIOPermissionAccess.Write, new String[] { fullPath }, false, false).Demand(); if (Directory.InternalExists(fullPath)) // Win9x hack to behave same as Winnt. Win9x fails silently for directories { throw new UnauthorizedAccessException(String.Format(Environment.GetResourceString("UnauthorizedAccess_IODenied_Path"), path)); } bool r = Win32Native.DeleteFile(fullPath); if (!r) { int hr = Marshal.GetLastWin32Error(); if (hr == Win32Native.ERROR_FILE_NOT_FOUND) { return; } else { __Error.WinIOError(hr, path); } } }
// Moves a given file to a new location and potentially a new file name. // This method does work across volumes. // // The caller must have certain FileIOPermissions. The caller must // have Read and Write permission to // sourceFileName and Write // permissions to destFileName. // /// <include file='doc\FileInfo.uex' path='docs/doc[@for="FileInfo.MoveTo"]/*' /> public void MoveTo(String destFileName) { if (destFileName == null) { throw new ArgumentNullException("destFileName"); } if (destFileName.Length == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName"); } new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, new String[] { FullPath }, false, false).Demand(); String fullDestFileName = Path.GetFullPathInternal(destFileName); new FileIOPermission(FileIOPermissionAccess.Write, new String[] { fullDestFileName }, false, false).Demand(); if (!Win32Native.MoveFile(FullPath, fullDestFileName)) { __Error.WinIOError(); } FullPath = fullDestFileName; OriginalPath = destFileName; _name = Path.GetFileName(fullDestFileName); // Flush any cached information about the file. _dataInitialised = -1; }
// Moves a specified file to a new location and potentially a new file name. // This method does work across volumes. // // The caller must have certain FileIOPermissions. The caller must // have Read and Write permission to // sourceFileName and Write // permissions to destFileName. // /// <include file='doc\File.uex' path='docs/doc[@for="File.Move"]/*' /> public static void Move(String sourceFileName, String destFileName) { if (sourceFileName == null || destFileName == null) { throw new ArgumentNullException((sourceFileName == null ? "sourceFileName" : "destFileName"), Environment.GetResourceString("ArgumentNull_FileName")); } if (sourceFileName.Length == 0 || destFileName.Length == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), (sourceFileName.Length == 0 ? "sourceFileName" : "destFileName")); } String fullSourceFileName = Path.GetFullPathInternal(sourceFileName); new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, new String[] { fullSourceFileName }, false, false).Demand(); String fullDestFileName = Path.GetFullPathInternal(destFileName); new FileIOPermission(FileIOPermissionAccess.Write, new String[] { fullDestFileName }, false, false).Demand(); if (!InternalExists(fullSourceFileName)) { __Error.WinIOError(Win32Native.ERROR_FILE_NOT_FOUND, sourceFileName); } if (!Win32Native.MoveFile(fullSourceFileName, fullDestFileName)) { int errorCode = Marshal.GetLastWin32Error(); __Error.WinIOError(errorCode, destFileName); } }
public void MoveTo(String destFileName) { if (destFileName == null) { throw new ArgumentNullException(nameof(destFileName)); } if (destFileName.Length == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(destFileName)); } Contract.EndContractBlock(); string fullDestFileName = Path.GetFullPath(destFileName); FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Write | FileSecurityStateAccess.Read, DisplayPath, FullPath); FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destFileName, fullDestFileName); sourceState.EnsureState(); destState.EnsureState(); if (!Win32Native.MoveFile(FullPath, fullDestFileName)) { __Error.WinIOError(); } FullPath = fullDestFileName; OriginalPath = destFileName; _name = Path.GetFileName(fullDestFileName); DisplayPath = GetDisplayPath(destFileName); // Flush any cached information about the file. _dataInitialised = -1; }
private static void InternalReplace(String sourceFileName, String destinationFileName, String destinationBackupFileName, bool ignoreMetadataErrors) { Contract.Requires(sourceFileName != null); Contract.Requires(destinationFileName != null); String fullSrcPath = Path.GetFullPath(sourceFileName); String fullDestPath = Path.GetFullPath(destinationFileName); String fullBackupPath = null; if (destinationBackupFileName != null) { fullBackupPath = Path.GetFullPath(destinationBackupFileName); } int flags = Win32Native.REPLACEFILE_WRITE_THROUGH; if (ignoreMetadataErrors) { flags |= Win32Native.REPLACEFILE_IGNORE_MERGE_ERRORS; } bool r = Win32Native.ReplaceFile(fullDestPath, fullSrcPath, fullBackupPath, flags, IntPtr.Zero, IntPtr.Zero); if (!r) { __Error.WinIOError(); } }
internal static void Move(String sourceDirName, String destDirName) { Contract.Requires(sourceDirName != null); Contract.Requires(destDirName != null); Contract.Requires(sourceDirName.Length != 0); Contract.Requires(destDirName.Length != 0); String fullsourceDirName = LongPath.NormalizePath(sourceDirName); String sourcePath = GetDemandDir(fullsourceDirName, false); if (sourcePath.Length >= Path.MaxLongPath) { throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong")); } String fulldestDirName = LongPath.NormalizePath(destDirName); String destPath = GetDemandDir(fulldestDirName, false); if (destPath.Length >= Path.MaxLongPath) { throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong")); } new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, new String[] { sourcePath }, false, false).Demand(); new FileIOPermission(FileIOPermissionAccess.Write, new String[] { destPath }, false, false).Demand(); if (String.Compare(sourcePath, destPath, StringComparison.OrdinalIgnoreCase) == 0) { throw new IOException(Environment.GetResourceString("IO.IO_SourceDestMustBeDifferent")); } String sourceRoot = LongPath.GetPathRoot(sourcePath); String destinationRoot = LongPath.GetPathRoot(destPath); if (String.Compare(sourceRoot, destinationRoot, StringComparison.OrdinalIgnoreCase) != 0) { throw new IOException(Environment.GetResourceString("IO.IO_SourceDestMustHaveSameRoot")); } String tempSourceDirName = Path.AddLongPathPrefix(sourceDirName); String tempDestDirName = Path.AddLongPathPrefix(destDirName); if (!Win32Native.MoveFile(tempSourceDirName, tempDestDirName)) { int hr = Marshal.GetLastWin32Error(); if (hr == Win32Native.ERROR_FILE_NOT_FOUND) // Source dir not found { hr = Win32Native.ERROR_PATH_NOT_FOUND; __Error.WinIOError(hr, fullsourceDirName); } // This check was originally put in for Win9x (unfortunately without special casing it to be for Win9x only). We can't change the NT codepath now for backcomp reasons. if (hr == Win32Native.ERROR_ACCESS_DENIED) // WinNT throws IOException. This check is for Win9x. We can't change it for backcomp. { throw new IOException(Environment.GetResourceString("UnauthorizedAccess_IODenied_Path", sourceDirName), Win32Native.MakeHRFromErrorCode(hr)); } __Error.WinIOError(hr, String.Empty); } }
[System.Security.SecurityCritical] // auto-generated internal static void WinIOError(int errorCode, String maybeFullPath) { // This doesn't have to be perfect, but is a perf optimization. bool isInvalidPath = errorCode == Win32Native.ERROR_INVALID_NAME || errorCode == Win32Native.ERROR_BAD_PATHNAME; String str = GetDisplayablePath(maybeFullPath, isInvalidPath); switch (errorCode) { case Win32Native.ERROR_FILE_NOT_FOUND: if (str.Length == 0) throw new FileNotFoundException(Environment.GetResourceString("IO.FileNotFound")); else throw new FileNotFoundException(Environment.GetResourceString("IO.FileNotFound_FileName", str), str); case Win32Native.ERROR_PATH_NOT_FOUND: if (str.Length == 0) throw new DirectoryNotFoundException(Environment.GetResourceString("IO.PathNotFound_NoPathName")); else throw new DirectoryNotFoundException(Environment.GetResourceString("IO.PathNotFound_Path", str)); case Win32Native.ERROR_ACCESS_DENIED: if (str.Length == 0) throw new UnauthorizedAccessException(Environment.GetResourceString("UnauthorizedAccess_IODenied_NoPathName")); else throw new UnauthorizedAccessException(Environment.GetResourceString("UnauthorizedAccess_IODenied_Path", str)); case Win32Native.ERROR_ALREADY_EXISTS: if (str.Length == 0) goto default; throw new IOException(Environment.GetResourceString("IO.IO_AlreadyExists_Name", str), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath); case Win32Native.ERROR_FILENAME_EXCED_RANGE: throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong")); case Win32Native.ERROR_INVALID_DRIVE: throw new DriveNotFoundException(Environment.GetResourceString("IO.DriveNotFound_Drive", str)); case Win32Native.ERROR_INVALID_PARAMETER: throw new IOException(Win32Native.GetMessage(errorCode), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath); case Win32Native.ERROR_SHARING_VIOLATION: if (str.Length == 0) throw new IOException(Environment.GetResourceString("IO.IO_SharingViolation_NoFileName"), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath); else throw new IOException(Environment.GetResourceString("IO.IO_SharingViolation_File", str), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath); case Win32Native.ERROR_FILE_EXISTS: if (str.Length == 0) goto default; throw new IOException(Environment.GetResourceString("IO.IO_FileExists_Name", str), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath); case Win32Native.ERROR_OPERATION_ABORTED: throw new OperationCanceledException(); default: throw new IOException(Win32Native.GetMessage(errorCode), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath); } }
public static void FreeHGlobal(IntPtr hglobal) { if (IsNotWin32Atom(hglobal)) { if (Win32Native.NULL != Win32Native.LocalFree(hglobal)) { ThrowExceptionForHR(GetHRForLastWin32Error()); } } }
public static IntPtr AllocHGlobal(IntPtr cb) { IntPtr pNewMem = Win32Native.LocalAlloc(LMEM_FIXED, cb); if (pNewMem == Win32Native.NULL) { throw new OutOfMemoryException(); } return(pNewMem); }
// Returns a unique temporary file name, and creates a 0-byte file by that // name on disk. /// <include file='doc\Path.uex' path='docs/doc[@for="Path.GetTempFileName"]/*' /> public static String GetTempFileName() { String path = GetTempPath(); StringBuilder sb = new StringBuilder(MAX_PATH); uint r = Win32Native.GetTempFileName(path, "tmp", 0, sb); if (r == 0) { __Error.WinIOError(); } return(sb.ToString()); }
internal static String InternalCopy(String sourceFileName, String destFileName, bool overwrite) { if (sourceFileName == null || destFileName == null) { throw new ArgumentNullException((sourceFileName == null ? "sourceFileName" : "destFileName"), Environment.GetResourceString("ArgumentNull_FileName")); } if (sourceFileName.Length == 0 || destFileName.Length == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), (sourceFileName.Length == 0 ? "sourceFileName" : "destFileName")); } String fullSourceFileName = Path.GetFullPathInternal(sourceFileName); new FileIOPermission(FileIOPermissionAccess.Read, new String[] { fullSourceFileName }, false, false).Demand(); String fullDestFileName = Path.GetFullPathInternal(destFileName); new FileIOPermission(FileIOPermissionAccess.Write, new String[] { fullDestFileName }, false, false).Demand(); bool r = Win32Native.CopyFile(fullSourceFileName, fullDestFileName, !overwrite); if (!r) { // Save Win32 error because subsequent checks will overwrite this HRESULT. int errorCode = Marshal.GetLastWin32Error(); String fileName = destFileName; if (errorCode != Win32Native.ERROR_FILE_EXISTS) { // 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. Try reading the source file. using (SafeFileHandle handle = Win32Native.UnsafeCreateFile(fullSourceFileName, FileStream.GENERIC_READ, FileShare.Read, null, FileMode.Open, 0, IntPtr.Zero)) { if (handle.IsInvalid) { fileName = sourceFileName; } } if (errorCode == Win32Native.ERROR_ACCESS_DENIED) { if (Directory.InternalExists(fullDestFileName)) { throw new IOException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Arg_FileIsDirectory_Name"), destFileName), Win32Native.ERROR_ACCESS_DENIED, fullDestFileName); } } } __Error.WinIOError(errorCode, fileName); } return(fullDestFileName); }
/// <include file='doc\Path.uex' path='docs/doc[@for="Path.GetTempPath"]/*' /> public static String GetTempPath() { new EnvironmentPermission(PermissionState.Unrestricted).Demand(); StringBuilder sb = new StringBuilder(MAX_PATH); uint r = Win32Native.GetTempPath(MAX_PATH, sb); String path = sb.ToString(); if (r == 0) { __Error.WinIOError(); } return(path); }
public unsafe static void SetLastWriteTimeUtc(String path, DateTime lastWriteTimeUtc) { SafeFileHandle handle; using (OpenFile(path, FileAccess.Write, out handle)) { Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(lastWriteTimeUtc.ToFileTimeUtc()); bool r = Win32Native.SetFileTime(handle, null, null, &fileTime); if (!r) { int errorCode = Marshal.GetLastWin32Error(); __Error.WinIOError(errorCode, path); } } }
/// <include file='doc\File.uex' path='docs/doc[@for="File.SetLastWriteTimeUtc"]/*' /> public static void SetLastWriteTimeUtc(String path, DateTime lastWriteTimeUtc) { IntPtr handle = Win32Native.INVALID_HANDLE_VALUE; FileStream fs = OpenFile(path, FileAccess.Write, ref handle); bool r = Win32Native.SetFileTime(handle, null, null, new long[] { lastWriteTimeUtc.ToFileTimeUtc() }); if (!r) { int errorCode = Marshal.GetLastWin32Error(); fs.Close(); __Error.WinIOError(errorCode, path); } fs.Close(); }
/// <include file='doc\WaitHandle.uex' path='docs/doc[@for="WaitHandle.Dispose"]/*' /> protected virtual void Dispose(bool explicitDisposing) { if (waitHandle != InvalidHandle) { lock (this) { if (waitHandle != InvalidHandle) { IntPtr copyOfHandle = waitHandle; waitHandle = InvalidHandle; Win32Native.CloseHandle(copyOfHandle); } } } }
public static void SetAttributes(String path, FileAttributes fileAttributes) { String fullPath = Path.GetFullPath(path); bool r = Win32Native.SetFileAttributes(fullPath, (int)fileAttributes); if (!r) { int hr = Marshal.GetLastWin32Error(); if (hr == ERROR_INVALID_PARAMETER) { throw new ArgumentException(Environment.GetResourceString("Arg_InvalidFileAttrs")); } __Error.WinIOError(hr, fullPath); } }
/// <include file='doc\File.uex' path='docs/doc[@for="File.SetLastWriteTime"]/*' /> public unsafe static void SetLastWriteTime(String path, DateTime lastWriteTime) { IntPtr handle = Win32Native.INVALID_HANDLE_VALUE; FileStream fs = OpenFile(path, FileAccess.Write, ref handle); Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(lastWriteTime.ToFileTime()); bool r = Win32Native.SetFileTime(handle, null, null, &fileTime); if (!r) { int errorCode = Marshal.GetLastWin32Error(); fs.Close(); __Error.WinIOError(errorCode, path); } fs.Close(); }
/// <include file='doc\File.uex' path='docs/doc[@for="File.SetAttributes"]/*' /> public static void SetAttributes(String path, FileAttributes fileAttributes) { String fullPath = Path.GetFullPathInternal(path); new FileIOPermission(FileIOPermissionAccess.Write, new String[] { fullPath }, false, false).Demand(); bool r = Win32Native.SetFileAttributes(fullPath, (int)fileAttributes); if (!r) { int hr = Marshal.GetLastWin32Error(); if (hr == ERROR_INVALID_PARAMETER || hr == ERROR_ACCESS_DENIED) // Hack for Win98 to which returns Access denied sometimes { throw new ArgumentException(Environment.GetResourceString("Arg_InvalidFileAttrs")); } __Error.WinIOError(hr, path); } }
// Deletes a file. The file specified by the designated path is deleted. // If the file does not exist, Delete succeeds without throwing // an exception. // // On NT, Delete will fail for a file that is open for normal I/O // or a file that is memory mapped. public override void Delete() { bool r = Win32Native.DeleteFile(FullPath); if (!r) { int hr = Marshal.GetLastWin32Error(); if (hr == Win32Native.ERROR_FILE_NOT_FOUND) { return; } else { __Error.WinIOError(hr, DisplayPath); } } }
public static String PtrToStringAuto(IntPtr ptr) { if (Win32Native.NULL == ptr) { return(null); } else if (IsWin32Atom(ptr)) { return(null); } else { int nc = Win32Native.lstrlen(ptr); StringBuilder sb = new StringBuilder(nc); Win32Native.lstrcpy(sb, ptr); return(sb.ToString()); } }
public static String PtrToStringUni(IntPtr ptr) { if (Win32Native.NULL == ptr) { return(null); } else if (IsWin32Atom(ptr)) { return(null); } else { int nc = Win32Native.lstrlenW(ptr); StringBuilder sb = new StringBuilder(nc); Win32Native.CopyMemoryUni(sb, ptr, new IntPtr(2 * (1 + nc))); return(sb.ToString()); } }
internal static int FillAttributeInfo(String path, ref Win32Native.WIN32_FILE_ATTRIBUTE_DATA data ,bool tryagain) { int dataInitialised = 0; if (tryagain) // someone has a handle to the file open, or other error { Win32Native.WIN32_FIND_DATA win95data; win95data = new Win32Native.WIN32_FIND_DATA (); // Remove trialing slash since this can cause grief to FindFirstFile. You will get an invalid argument error String tempPath = path.TrimEnd(new char [] {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar}); // For floppy drives, normally the OS will pop up a dialog saying // there is no disk in drive A:, please insert one. We don't want that. // SetErrorMode will let us disable this, but we should set the error // mode back, since this may have wide-ranging effects. int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS); IntPtr handle = Win32Native.FindFirstFile(tempPath,win95data); Win32Native.SetErrorMode(oldMode); if (handle == Win32Native.INVALID_HANDLE_VALUE) { dataInitialised = Marshal.GetLastWin32Error(); if (dataInitialised == Win32Native.ERROR_FILE_NOT_FOUND || dataInitialised == Win32Native.ERROR_PATH_NOT_FOUND || dataInitialised == Win32Native.ERROR_NOT_READY) // floppy device not ready { data.fileAttributes = -1; dataInitialised = 0; } return dataInitialised; } // Close the Win32 handle Win32Native.FindClose(handle); // Copy the information to data data.fileAttributes = win95data.dwFileAttributes; data.ftCreationTimeLow = (uint)win95data.ftCreationTime_dwLowDateTime; data.ftCreationTimeHigh = (uint)win95data.ftCreationTime_dwHighDateTime; data.ftLastAccessTimeLow = (uint)win95data.ftLastAccessTime_dwLowDateTime; data.ftLastAccessTimeHigh = (uint)win95data.ftLastAccessTime_dwHighDateTime; data.ftLastWriteTimeLow = (uint)win95data.ftLastWriteTime_dwLowDateTime; data.ftLastWriteTimeHigh = (uint)win95data.ftLastWriteTime_dwHighDateTime; data.fileSizeHigh = win95data.nFileSizeHigh; data.fileSizeLow = win95data.nFileSizeLow; } else { // For floppy drives, normally the OS will pop up a dialog saying // there is no disk in drive A:, please insert one. We don't want that. // SetErrorMode will let us disable this, but we should set the error // mode back, since this may have wide-ranging effects. int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS); bool success = Win32Native.GetFileAttributesEx(path, GetFileExInfoStandard, ref data); Win32Native.SetErrorMode(oldMode); if (!success) { dataInitialised = Marshal.GetLastWin32Error(); if (dataInitialised == Win32Native.ERROR_FILE_NOT_FOUND || dataInitialised == Win32Native.ERROR_PATH_NOT_FOUND || dataInitialised == Win32Native.ERROR_NOT_READY) // floppy device not ready { data.fileAttributes = -1; dataInitialised = 0; } else { // In case someone latched onto the file. Take the perf hit only for failure return FillAttributeInfo(path,ref data,true); } } } return dataInitialised; }
internal static int FillAttributeInfo(String path, ref Win32Native.WIN32_FILE_ATTRIBUTE_DATA data, bool tryagain, bool returnErrorOnNotFound) { int dataInitialised = 0; if (tryagain) // someone has a handle to the file open, or other error { Win32Native.WIN32_FIND_DATA win95data; // We do this only on Win95 machines win95data = new Win32Native.WIN32_FIND_DATA (); // Remove trialing slash since this can cause grief to FindFirstFile. You will get an invalid argument error String tempPath = path.TrimEnd(new char [] {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar}); // For floppy drives, normally the OS will pop up a dialog saying // there is no disk in drive A:, please insert one. We don't want that. // SetErrorMode will let us disable this, but we should set the error // mode back, since this may have wide-ranging effects. int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS); try { bool error = false; SafeFindHandle handle = Win32Native.FindFirstFile(tempPath,win95data); try { if (handle.IsInvalid) { error = true; dataInitialised = Marshal.GetLastWin32Error(); if (dataInitialised == Win32Native.ERROR_FILE_NOT_FOUND || dataInitialised == Win32Native.ERROR_PATH_NOT_FOUND || dataInitialised == Win32Native.ERROR_NOT_READY) // floppy device not ready { if (!returnErrorOnNotFound) { // Return default value for backward compbatibility dataInitialised = 0; data.fileAttributes = -1; } } return dataInitialised; } } finally { // Close the Win32 handle try { handle.Close(); } catch { // if we're already returning an error, don't throw another one. if (!error) { BCLDebug.Assert(false, "File::FillAttributeInfo - FindClose failed!"); __Error.WinIOError(); } } } } finally { Win32Native.SetErrorMode(oldMode); } // Copy the information to data data.fileAttributes = win95data.dwFileAttributes; data.ftCreationTimeLow = (uint)win95data.ftCreationTime_dwLowDateTime; data.ftCreationTimeHigh = (uint)win95data.ftCreationTime_dwHighDateTime; data.ftLastAccessTimeLow = (uint)win95data.ftLastAccessTime_dwLowDateTime; data.ftLastAccessTimeHigh = (uint)win95data.ftLastAccessTime_dwHighDateTime; data.ftLastWriteTimeLow = (uint)win95data.ftLastWriteTime_dwLowDateTime; data.ftLastWriteTimeHigh = (uint)win95data.ftLastWriteTime_dwHighDateTime; data.fileSizeHigh = win95data.nFileSizeHigh; data.fileSizeLow = win95data.nFileSizeLow; } else { // For floppy drives, normally the OS will pop up a dialog saying // there is no disk in drive A:, please insert one. We don't want that. // SetErrorMode will let us disable this, but we should set the error // mode back, since this may have wide-ranging effects. bool success = false; int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS); try { success = Win32Native.GetFileAttributesEx(path, GetFileExInfoStandard, ref data); } finally { Win32Native.SetErrorMode(oldMode); } if (!success) { dataInitialised = Marshal.GetLastWin32Error(); if (dataInitialised != Win32Native.ERROR_FILE_NOT_FOUND && dataInitialised != Win32Native.ERROR_PATH_NOT_FOUND && dataInitialised != Win32Native.ERROR_NOT_READY) // floppy device not ready { // In case someone latched onto the file. Take the perf hit only for failure return FillAttributeInfo(path, ref data, true, returnErrorOnNotFound); } else { if (!returnErrorOnNotFound) { // Return default value for backward compbatibility dataInitialised = 0; data.fileAttributes = -1; } } } } return dataInitialised; }