public void GetFileAttributesLongPath() { string longPath = @"\\?\" + PathGenerator.CreatePathOfLength(@"C:\", 300); Action action = () => FileMethods.GetFileAttributes(longPath); action.ShouldThrow <System.IO.DirectoryNotFoundException>(); }
public void GetMultipleStreamInfoByHandle() { using (var temp = new TestFileCleaner()) { string source = temp.GetTestPath(); using (var file = FileMethods.CreateFile(source, DesiredAccess.GENERIC_READ, ShareMode.FILE_SHARE_READWRITE, CreationDisposition.CREATE_NEW)) { file.IsInvalid.Should().BeFalse(); } string destination = temp.GetTestPath(); FileMethods.CopyFile(source, destination); string alternateStream = destination + @":Foo:$DATA"; FileMethods.CopyFile(source, alternateStream); using (var file = FileMethods.CreateFile(destination, DesiredAccess.GENERIC_READ | DesiredAccess.GENERIC_WRITE, ShareMode.FILE_SHARE_READWRITE, CreationDisposition.OPEN_EXISTING)) { var fileInfo = FileMethods.GetStreamInformationByHandle(file); fileInfo.Should().BeEquivalentTo(new StreamInformation[] { new StreamInformation { Name = @"::$DATA" }, new StreamInformation { Name = @":Foo:$DATA" } }); } } }
public void GetFullPathNameForCurrent() { string fullPath = FileMethods.GetFullPathName("."); fullPath.Length.Should().BeGreaterThan(2); fullPath[1].Should().Be(':'); }
public void GetFileAttributesExBasic() { string tempPath = FileMethods.GetTempPath(); var info = FileMethods.GetFileAttributesEx(tempPath); info.Attributes.Should().HaveFlag(FileAttributes.FILE_ATTRIBUTE_DIRECTORY); }
public void GetBasicInfoByHandleBasic() { string tempPath = FileMethods.GetTempPath(); string tempFileName = System.IO.Path.Combine(tempPath, System.IO.Path.GetRandomFileName()); try { using (var directory = FileMethods.CreateFile(tempPath, DesiredAccess.GENERIC_READ, ShareMode.FILE_SHARE_READWRITE, CreationDisposition.OPEN_EXISTING, FileAttributes.NONE, FileFlags.FILE_FLAG_BACKUP_SEMANTICS)) { var directoryInfo = FileMethods.GetFileBasicInfoByHandle(directory); directoryInfo.Attributes.Should().HaveFlag(FileAttributes.FILE_ATTRIBUTE_DIRECTORY); using (var file = FileMethods.CreateFile(tempFileName, DesiredAccess.GENERIC_READ | DesiredAccess.GENERIC_WRITE, ShareMode.FILE_SHARE_READWRITE, CreationDisposition.CREATE_NEW)) { var fileInfo = FileMethods.GetFileBasicInfoByHandle(file); fileInfo.Attributes.Should().NotHaveFlag(FileAttributes.FILE_ATTRIBUTE_DIRECTORY); fileInfo.CreationTime.Should().BeAfter(directoryInfo.CreationTime); } } } finally { FileMethods.DeleteFile(tempFileName); } }
// Write a single byte to this stream. public override void WriteByte(byte value) { // Lock down the file stream while we do this. lock (this) { // Setup the object for writing. SetupWrite(); // Flush the current buffer if it is full. if (bufferPosn >= bufferSize) { if (!FileMethods.Write (handle, this.buffer, 0, bufferPosn)) { throw new IOException (FileMethods.GetErrno(), _("IO_WriteFailed")); } bufferPosn = 0; } // Write the byte into the buffer and advance the posn. buffer[bufferPosn++] = value; ++position; } }
private void CleanOwnFiles() { lock (s_CleanLock) { _flagFile.Dispose(); _flagFile = null; // Delete our own temp folder try { FileHelper.DeleteDirectoryRecursive(@"\\?\" + TempFolder); } catch (Exception) { } // Clean any loose files we're tracking foreach (string file in _filesToClean.Distinct(StringComparer.OrdinalIgnoreCase)) { if (string.IsNullOrWhiteSpace(file)) { continue; } try { FileMethods.DeleteFile(@"\\?\" + file); } catch (Exception) { } } } }
public void FinalPathNameLongPath() { using (var cleaner = new TestFileCleaner()) { string longPath = @"\\?\" + PathGenerator.CreatePathOfLength(cleaner.TempFolder, 500); string filePath = Paths.Combine(longPath, System.IO.Path.GetRandomFileName()); FileHelper.CreateDirectoryRecursive(longPath); FileHelper.WriteAllText(filePath, "FinalPathNameLongPathPrefixRoundTripBehavior"); using (var handle = FileMethods.CreateFile(filePath, DesiredAccess.GENERIC_READ, ShareMode.FILE_SHARE_READWRITE, CreationDisposition.OPEN_EXISTING)) { handle.IsInvalid.Should().BeFalse(); FileDesktopMethods.GetFinalPathNameByHandle(handle, GetFinalPathNameByHandleFlags.FILE_NAME_NORMALIZED) .Should().Be(filePath); FileDesktopMethods.GetFinalPathNameByHandle(handle, GetFinalPathNameByHandleFlags.FILE_NAME_OPENED) .Should().Be(filePath); FileDesktopMethods.GetFinalPathNameByHandle(handle, GetFinalPathNameByHandleFlags.VOLUME_NAME_DOS) .Should().Be(filePath); FileDesktopMethods.GetFinalPathNameByHandle(handle, GetFinalPathNameByHandleFlags.VOLUME_NAME_GUID) .Should().StartWith(@"\\?\Volume"); FileDesktopMethods.GetFinalPathNameByHandle(handle, GetFinalPathNameByHandleFlags.VOLUME_NAME_NT) .Should().StartWith(@"\Device\"); FileDesktopMethods.GetFinalPathNameByHandle(handle, GetFinalPathNameByHandleFlags.VOLUME_NAME_NONE) .Should().Be(filePath.Substring(6)); } } }
public void GetShortNameBasic() { string tempPath = FileMethods.GetTempPath(); using (var directory = FileMethods.CreateFile(tempPath, DesiredAccess.GENERIC_READ, ShareMode.FILE_SHARE_READWRITE, CreationDisposition.OPEN_EXISTING, FileAttributes.NONE, FileFlags.FILE_FLAG_BACKUP_SEMANTICS)) { // This will give back the NT volume path (\Device\HarddiskVolumen\) string directoryName = FileDesktopMethods.GetShortName(directory); directoryName.Should().Be("Temp"); string tempFileName = "ExtraLongName" + System.IO.Path.GetRandomFileName(); string tempFilePath = System.IO.Path.Combine(tempPath, tempFileName); try { using (var file = FileMethods.CreateFile(tempFilePath, DesiredAccess.GENERIC_READ, ShareMode.FILE_SHARE_READWRITE, CreationDisposition.CREATE_NEW)) { string fileName = FileDesktopMethods.GetShortName(file); fileName.Length.Should().BeLessOrEqualTo(12); } } finally { FileMethods.DeleteFile(tempFilePath); } } }
public void GetFileAttributesExBasic() { string tempPath = FileMethods.GetTempPath(); var info = FileMethods.GetFileAttributesEx(tempPath); info.dwFileAttributes.Should().HaveFlag(FileAttributes.Directory); }
public void GetMultipleStreamInfoByHandle() { using (var temp = new TestFileCleaner()) { string source = temp.GetTestPath(); using (var file = FileMethods.CreateFile(source, CreationDisposition.CreateNew)) { file.IsInvalid.Should().BeFalse(); } string destination = temp.GetTestPath(); FileMethods.CopyFile(source, destination); string alternateStream = destination + @":Foo:$DATA"; FileMethods.CopyFile(source, alternateStream); using (var file = FileMethods.CreateFile(destination, CreationDisposition.OpenExisting)) { var fileInfo = FileMethods.GetStreamInformation(file); fileInfo.Should().BeEquivalentTo(new StreamInformation[] { new StreamInformation { Name = @"::$DATA" }, new StreamInformation { Name = @":Foo:$DATA" } }); } } }
public void FinalPathNameBasic() { using (var cleaner = new TestFileCleaner()) { string filePath = cleaner.CreateTestFile("FinalPathNameBehavior"); using (var handle = FileMethods.CreateFile(filePath.ToLower(), CreationDisposition.OpenExisting, DesiredAccess.GenericRead)) { handle.IsInvalid.Should().BeFalse(); string extendedPath = @"\\?\" + filePath; FileMethods.GetFinalPathNameByHandle(handle, GetFinalPathNameByHandleFlags.FILE_NAME_NORMALIZED) .Should().Be(extendedPath); FileMethods.GetFinalPathNameByHandle(handle, GetFinalPathNameByHandleFlags.FILE_NAME_OPENED) .Should().Be(extendedPath); FileMethods.GetFinalPathNameByHandle(handle, GetFinalPathNameByHandleFlags.VOLUME_NAME_DOS) .Should().Be(extendedPath); FileMethods.GetFinalPathNameByHandle(handle, GetFinalPathNameByHandleFlags.VOLUME_NAME_GUID) .Should().StartWith(@"\\?\Volume"); FileMethods.GetFinalPathNameByHandle(handle, GetFinalPathNameByHandleFlags.VOLUME_NAME_NT) .Should().StartWith(@"\Device\"); FileMethods.GetFinalPathNameByHandle(handle, GetFinalPathNameByHandleFlags.VOLUME_NAME_NONE) .Should().Be(filePath.Substring(2)); } } }
public void GetDirectoryFilenames_SpecialDirectories() { // The "." and ".." entries returned vary quite a bit using (var handle = DirectoryMethods.CreateDirectoryHandle(@"C:\")) { string[] names = FileMethods.GetDirectoryFilenames(handle).ToArray(); names.Should().NotContain("."); names.Should().NotContain(".."); } using (var handle = DirectoryMethods.CreateDirectoryHandle(FileMethods.GetTempPath())) { string[] names = FileMethods.GetDirectoryFilenames(handle).ToArray(); names.Should().Contain("."); names.Should().NotContain(".."); } using (var cleaner = new TestFileCleaner()) { string directory = cleaner.GetTestPath(); DirectoryMethods.CreateDirectory(directory); using (var handle = DirectoryMethods.CreateDirectoryHandle(FileMethods.GetTempPath())) { string[] names = FileMethods.GetDirectoryFilenames(handle).ToArray(); names.Should().Contain("."); names.Should().Contain(".."); } } }
public void GetShortNameBasic() { string tempPath = FileMethods.GetTempPath(); using (var directory = DirectoryMethods.CreateDirectoryHandle(tempPath)) { // This will give back the NT volume path (\Device\HarddiskVolumen\) string directoryName = FileMethods.GetShortName(directory); directoryName.Should().Be("Temp"); string tempFileName = "ExtraLongName" + System.IO.Path.GetRandomFileName(); string tempFilePath = System.IO.Path.Combine(tempPath, tempFileName); try { using (var file = FileMethods.CreateFile(tempFilePath, CreationDisposition.CreateNew, DesiredAccess.GenericRead)) { string fileName = FileMethods.GetShortName(file); fileName.Length.Should().BeLessOrEqualTo(12); } } finally { FileMethods.DeleteFile(tempFilePath); } } }
// Read a single byte from this stream. public override int ReadByte() { // Lock down the file stream while we do this. lock (this) { // Setup the object for reading. SetupRead(); // Read more data into the internal buffer if necessary. if (bufferPosn >= bufferLen) { bufferPosn = 0; bufferLen = FileMethods.Read (handle, buffer, 0, bufferSize); if (bufferLen < 0) { bufferLen = 0; throw new IOException (FileMethods.GetErrno(), _("IO_ReadFailed")); } else if (bufferLen == 0) { // We've reached EOF. return(-1); } } // Extract the next byte from the buffer. ++position; return(buffer[bufferPosn++]); } }
public void FinalPathNameVolumeNameBehavior() { // This test is asserting that the original volume name has nothing to do with the volume GetFinalPathNameByHandle returns using (var cleaner = new TestFileCleaner()) { string filePath = cleaner.CreateTestFile("FinalPathNameVolumeNameBehavior"); using (var handle = FileMethods.CreateFile(filePath.ToLower(), DesiredAccess.GENERIC_READ, ShareMode.FILE_SHARE_READWRITE, CreationDisposition.OPEN_EXISTING)) { handle.IsInvalid.Should().BeFalse(); string extendedPath = @"\\?\" + filePath; FileDesktopMethods.GetFinalPathNameByHandle(handle, GetFinalPathNameByHandleFlags.FILE_NAME_NORMALIZED) .Should().Be(extendedPath); FileDesktopMethods.GetFinalPathNameByHandle(handle, GetFinalPathNameByHandleFlags.FILE_NAME_OPENED) .Should().Be(extendedPath); FileDesktopMethods.GetFinalPathNameByHandle(handle, GetFinalPathNameByHandleFlags.VOLUME_NAME_DOS) .Should().Be(extendedPath); FileDesktopMethods.GetFinalPathNameByHandle(handle, GetFinalPathNameByHandleFlags.VOLUME_NAME_GUID) .Should().StartWith(@"\\?\Volume"); FileDesktopMethods.GetFinalPathNameByHandle(handle, GetFinalPathNameByHandleFlags.VOLUME_NAME_NT) .Should().StartWith(@"\Device\"); FileDesktopMethods.GetFinalPathNameByHandle(handle, GetFinalPathNameByHandleFlags.VOLUME_NAME_NONE) .Should().Be(filePath.Substring(2)); } } }
// Set the length of this stream. public override void SetLength(long value) { // Validate the parameters and setup the object for writing. if (value < 0) { throw new ArgumentOutOfRangeException ("value", _("ArgRange_NonNegative")); } if (!canSeek) { throw new NotSupportedException(_("IO_NotSupp_Seek")); } // Lock down the file stream while we do this. lock (this) { // Setup this object for writing. SetupWrite(); // Call the underlying platform's "SetLength" method. if (!FileMethods.SetLength(handle, value)) { throw new IOException (FileMethods.GetErrno(), _("IO_SetLengthFailed")); } } }
public static void foo() { Person person = new Person { Age = 25, Name = "Larry", Salary = 12500.50 }; string path = Directory.GetCurrentDirectory(); string fileName = @"person.json"; string json = JsonSerializer.Serialize(person); Console.WriteLine($"Person в JSON: {json}"); FileMethods.WriteFile(path, fileName, json); string jsonFromFile = FileMethods.ReadFile(path, fileName); Person personFromJson = JsonSerializer.Deserialize <Person>(jsonFromFile); Console.WriteLine(personFromJson); Console.WriteLine("Нажмите любую кнопку для удаления файла..."); Console.ReadKey(true); FileMethods.DeleteFile(path, fileName); Console.WriteLine("========================"); }
// Unlock a region of the file stream. public virtual void Unlock(long position, long length) { if (position < 0) { throw new ArgumentOutOfRangeException ("position", _("ArgRange_NonNegative")); } if (length < 0) { throw new ArgumentOutOfRangeException ("position", _("ArgRange_NonNegative")); } lock (this) { if (handle == invalidHandle) { throw new ObjectDisposedException(_("IO_StreamClosed")); } if (!FileMethods.Unlock(handle, position, length)) { throw new IOException (FileMethods.GetErrno(), _("IO_UnlockFailed")); } } }
// Set the creation time on a file. public static void SetCreationTime(String path, DateTime creationTime) { Directory.ValidatePath(path); Directory.HandleErrorsFile (FileMethods.SetCreationTime (path, creationTime.ToUniversalTime().Ticks)); }
private static void CleanOrphanedTempFolders() { // Clean up orphaned temp folders DirectoryInfo rootInfo = new DirectoryInfo(s_rootTempFolder); if (rootInfo != null) { try { var flagFiles = from directory in rootInfo.EnumerateDirectories() from file in directory.EnumerateFiles(WinteropFlagFileName) select new { Directory = directory.FullName, File = file.FullName }; foreach (var flagFile in flagFiles.ToArray()) { try { // If we can't delete the flag file (open handle) we'll throw and move on FileMethods.DeleteFile(@"\\?\" + flagFile.File); FileHelper.DeleteDirectoryRecursive(@"\\?\" + flagFile.Directory); } catch (Exception) { } } } catch (Exception) { // Ignoring orphan cleanup errors as the DotNet file service chokes on long paths } } }
// Set the last access time on a file. public static void SetLastAccessTime(String path, DateTime lastAccessTime) { Directory.ValidatePath(path); Directory.HandleErrorsFile (FileMethods.SetLastAccessTime (path, lastAccessTime.ToUniversalTime().Ticks)); }
public void GetStandardInfoByHandleBasic() { string tempPath = FileMethods.GetTempPath(); string tempFileName = System.IO.Path.Combine(tempPath, System.IO.Path.GetRandomFileName()); try { using (var directory = FileMethods.CreateFile(tempPath, DesiredAccess.GENERIC_READWRITE, ShareMode.FILE_SHARE_READWRITE, CreationDisposition.OPEN_EXISTING, FileAttributes.NONE, FileFlags.FILE_FLAG_BACKUP_SEMANTICS)) { var info = FileMethods.GetFileStandardInfoByHandle(directory); info.Directory.Should().BeTrue(); } using (var file = FileMethods.CreateFile(tempFileName, DesiredAccess.GENERIC_READWRITE, ShareMode.FILE_SHARE_READWRITE, CreationDisposition.CREATE_NEW)) { var info = FileMethods.GetFileStandardInfoByHandle(file); info.Directory.Should().BeFalse(); info.NumberOfLinks.Should().Be(1); info.DeletePending.Should().BeFalse(); info.AllocationSize.Should().Be(0); info.EndOfFile.Should().Be(0); } } finally { FileMethods.DeleteFile(tempFileName); } }
// Set the attributes on a file. public static void SetAttributes (String path, FileAttributes fileAttributes) { Directory.ValidatePath(path); Directory.HandleErrorsFile (FileMethods.SetAttributes(path, (int)fileAttributes)); }
public void GetStreamInfoByHandleBasic() { string tempPath = FileMethods.GetTempPath(); string tempFileName = System.IO.Path.Combine(tempPath, System.IO.Path.GetRandomFileName()); try { using (var directory = FileMethods.CreateFile(tempPath, DesiredAccess.GENERIC_READ, ShareMode.FILE_SHARE_READWRITE, CreationDisposition.OPEN_EXISTING, FileAttributes.NONE, FileFlags.FILE_FLAG_BACKUP_SEMANTICS)) { var directoryInfo = FileMethods.GetStreamInformationByHandle(directory); directoryInfo.Should().BeEmpty(); using (var file = FileMethods.CreateFile(tempFileName, DesiredAccess.GENERIC_READ | DesiredAccess.GENERIC_WRITE, ShareMode.FILE_SHARE_READWRITE, CreationDisposition.CREATE_NEW)) { var fileInfo = FileMethods.GetStreamInformationByHandle(file); fileInfo.Should().HaveCount(1); var info = fileInfo.First(); info.Name.Should().Be(@"::$DATA"); info.Size.Should().Be(0); info.AllocationSize.Should().Be(0); } } } finally { FileMethods.DeleteFile(tempFileName); } }
// Set the UTC last modification time on a file. public static void SetLastWriteTimeUtc(String path, DateTime lastWriteTime) { Directory.ValidatePath(path); Directory.HandleErrorsFile (FileMethods.SetLastWriteTime (path, lastWriteTime.Ticks)); }
public void FindFirstFileNoFiles() { using (var find = FileMethods.CreateFindOperation(FileMethods.GetTempPath() + System.IO.Path.GetRandomFileName())) { find.GetNextResult().Should().BeNull(); } }
// Flush the pending contents in this stream. public override void Flush() { lock (this) { if (handle != invalidHandle) { if (bufferOwnedByWrite) { FlushWriteBuffer(); if (!FileMethods.FlushWrite(handle)) { throw new IOException (FileMethods.GetErrno(), _("IO_FlushFailed")); } } else { FlushReadBuffer(); } } else { throw new ObjectDisposedException (_("IO_StreamClosed")); } } }
public static IEnumerable <BackupStreamInformation> GetAlternateStreamInformation(string path) { List <BackupStreamInformation> streams = new List <BackupStreamInformation>(); using (var fileHandle = FileMethods.CreateFile( path: path, // To look at metadata we don't need read or write access desiredAccess: 0, shareMode: ShareMode.FILE_SHARE_READWRITE, creationDisposition: CreationDisposition.OPEN_EXISTING, fileAttributes: FileAttributes.NONE, fileFlags: FileFlags.FILE_FLAG_BACKUP_SEMANTICS)) { using (BackupReader reader = new BackupReader(fileHandle)) { BackupStreamInformation?info; while ((info = reader.GetNextInfo()).HasValue) { if (info.Value.StreamType == BackupStreamType.BACKUP_ALTERNATE_DATA) { streams.Add(new BackupStreamInformation { Name = info.Value.Name, Size = info.Value.Size }); } } } } return(streams); }
private async Task <ProjectItem> SimulateCustomTool() { string outputFileName = Path.Combine(Path.GetDirectoryName(this.project.FullName), this.input.GetItemAttribute(ItemMetadata.LastGenOutput)); ProjectItem outputItem = this.input.ProjectItems.Cast <ProjectItem>().SingleOrDefault(item => item.FileNames[1] == outputFileName); if (outputItem != null) { if (Path.GetExtension(outputFileName) == this.templatingCallback.Extension) { // Required output file exists. Touch it and return. File.SetLastWriteTime(outputFileName, DateTime.UtcNow); await Dispatcher.Yield(); return(outputItem); } // Output file has a wrong name, delete it. outputItem.Delete(); } // Create the new output file outputFileName = Path.ChangeExtension(this.input.FileNames[1], this.templatingCallback.Extension); this.input.SetItemAttribute(ItemMetadata.LastGenOutput, FileMethods.GetRelativePath(this.project.FullName, outputFileName).TrimStart('.', '\\')); outputItem = IntegrationTest.CreateTestProjectItemFromFile(this.input.ProjectItems, outputFileName); await Dispatcher.Yield(); return(outputItem); }