C# File.Open的代码示例
通过代码示例来学习C# File.Open方法
通过代码示例来学习编程是非常高效的。
1. 代码示例提供了一个具体而直观的学习环境,使初学者能够立即看到编程概念和语法的实际应用。
2. 通过分析和模仿现有的代码实例,初学者可以更好地理解编程逻辑和算法的工作原理。
3. 代码实例往往涵盖了多种编程技巧和最佳实践,通过学习和模仿这些实例,学习者可以逐步掌握如何编写高效、可读性强和可维护的代码。这对于初学者来说,是一种快速提升编程水平的有效途径。
File.Open是C#的System.IO命名空间下中的一个方法, 小编为大家找了一些网络大拿们常见的代码示例,源码中的File.Open() 已经帮大家高亮显示了,大家可以重点学习File.Open() 方法的写法,从而快速掌握该方法的应用。
File.Open的代码示例1 - IniCheckPermissions()
using System.IO; bool IniCheckPermissions() { bool deleteAfter = !File.Exists(IniFilename); bool hasPermission = false; try { using (FileStream fileStream = File.Open(IniFilename, FileMode.OpenOrCreate, FileAccess.Write)) { hasPermission = true; } } catch { hasPermission = false; } if (File.Exists(IniFilename) && deleteAfter) try { File.Delete(IniFilename); } catch { } return hasPermission; }
开发者ID:emoose,项目名称:DLSSTweaks,代码行数:28,代码来源:Main.cs
在IniCheckPermissions()方法中,File的代码示例类中的Open的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞
File.Open的代码示例2 - FilesAreBufferedAndCanBeFlushed()
using System.IO; [TestCaseSource(typeof(FileRunnersAndFolders), nameof(FileRunnersAndFolders.Runners))] public void FilesAreBufferedAndCanBeFlushed(FileSystemRunner fileSystem, string parentFolder) { string filename = Path.Combine(parentFolder, "FilesAreBufferedAndCanBeFlushed"); string filePath = this.Enlistment.GetVirtualPathTo(filename); byte[] buffer = System.Text.Encoding.ASCII.GetBytes("Some test data"); using (FileStream writeStream = File.Open(filePath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite)) { writeStream.Write(buffer, 0, buffer.Length); using (FileStream readStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) { readStream.Length.ShouldEqual(0); writeStream.Flush(); readStream.Length.ShouldEqual(buffer.Length); byte[] readBuffer = new byte[buffer.Length]; readStream.Read(readBuffer, 0, readBuffer.Length).ShouldEqual(readBuffer.Length); readBuffer.ShouldMatchInOrder(buffer); } } fileSystem.DeleteFile(filePath); }
开发者ID:microsoft,项目名称:VFSForGit,代码行数:28,代码来源:BasicFileSystemTests.cs
在FilesAreBufferedAndCanBeFlushed()方法中,File的代码示例类中的Open的代码示例方法一共出现了3次, 见黄色背景高亮显示的地方,欢迎大家点赞
File.Open的代码示例3 - SavePersistedValue()
using System.IO; private static void SavePersistedValue(string dotGVFSRoot, string key, string value) { string metadataPath = Path.Combine(dotGVFSRoot, RepoMetadataName); Dictionary
repoMetadata = new Dictionary (); string json; using (FileStream fs = new FileStream(metadataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) using (StreamReader reader = new StreamReader(fs)) { while (!reader.EndOfStream) { json = reader.ReadLine(); json.Substring(0, 2).ShouldEqual("A "); KeyValuePair kvp = JsonConvert.DeserializeObject >(json.Substring(2)); repoMetadata.Add(kvp.Key, kvp.Value); } } repoMetadata[key] = value; string newRepoMetadataContents = string.Empty; foreach (KeyValuePair kvp in repoMetadata) { newRepoMetadataContents += "A " + JsonConvert.SerializeObject(kvp).Trim() + "\r\n"; } File.WriteAllText(metadataPath, newRepoMetadataContents); }
开发者ID:microsoft,项目名称:VFSForGit,代码行数:32,代码来源:GVFSHelpers.cs
在SavePersistedValue()方法中,File的代码示例类中的Open的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞
File.Open的代码示例4 - ServiceLogContainsUpgradeMessaging()
using System.IO; private bool ServiceLogContainsUpgradeMessaging() { // This test checks for the upgrade timer start message in the Service log // file. GVFS.Service should schedule the timer as it starts. string expectedTimerMessage = "Checking for product upgrades. (Start)"; string serviceLogFolder = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "GVFS", GVFSServiceProcess.TestServiceName, "Logs"); DirectoryInfo logsDirectory = new DirectoryInfo(serviceLogFolder); FileInfo logFile = logsDirectory.GetFiles() .OrderByDescending(f => f.LastWriteTime) .FirstOrDefault(); if (logFile != null) { using (StreamReader fileStream = new StreamReader(File.Open(logFile.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))) { string nextLine = null; while ((nextLine = fileStream.ReadLine()) != null) { if (nextLine.Contains(expectedTimerMessage)) { return true; } } } } return false; }
开发者ID:microsoft,项目名称:VFSForGit,代码行数:34,代码来源:GVFSUpgradeReminderTests.cs
在ServiceLogContainsUpgradeMessaging()方法中,File的代码示例类中的Open的代码示例方法一共出现了2次, 见黄色背景高亮显示的地方,欢迎大家点赞
File.Open的代码示例5 - OpenFileThenCheckout()
using System.IO; [TestCase] public void OpenFileThenCheckout() { string virtualFile = Path.Combine(this.Enlistment.RepoRoot, GitCommandsTests.EditFilePath); string controlFile = Path.Combine(this.ControlGitRepo.RootPath, GitCommandsTests.EditFilePath); // Open files with ReadWrite sharing because depending on the state of the index (and the mtimes), git might need to read the file // as part of status (while we have the handle open). using (FileStream virtualFS = File.Open(virtualFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite)) using (StreamWriter virtualWriter = new StreamWriter(virtualFS)) using (FileStream controlFS = File.Open(controlFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite)) using (StreamWriter controlWriter = new StreamWriter(controlFS)) { this.ValidateGitCommand("checkout -b tests/functional/OpenFileThenCheckout"); virtualWriter.WriteLine("// Adding a line for testing purposes"); controlWriter.WriteLine("// Adding a line for testing purposes"); this.ValidateGitCommand("status"); } // NOTE: Due to optimizations in checkout -b, the modified files will not be included as part of the // success message. Validate that the succcess messages match, and the call to validate "status" below // will ensure that GVFS is still reporting the edited file as modified. string controlRepoRoot = this.ControlGitRepo.RootPath; string gvfsRepoRoot = this.Enlistment.RepoRoot; string command = "checkout -b tests/functional/OpenFileThenCheckout_2"; ProcessResult expectedResult = GitProcess.InvokeProcess(controlRepoRoot, command); ProcessResult actualResult = GitHelpers.InvokeGitAgainstGVFSRepo(gvfsRepoRoot, command); GitHelpers.ErrorsShouldMatch(command, expectedResult, actualResult); actualResult.Errors.ShouldContain("Switched to a new branch"); this.ValidateGitCommand("status"); }
开发者ID:microsoft,项目名称:VFSForGit,代码行数:35,代码来源:GitCommandsTests.cs
在OpenFileThenCheckout()方法中,File的代码示例类中的Open的代码示例方法一共出现了2次, 见黄色背景高亮显示的地方,欢迎大家点赞
File.Open的代码示例6 - OpenIndexForRead()
using System.IO; public virtual FileSystemTaskResult OpenIndexForRead() { if (!File.Exists(this.indexPath)) { EventMetadata metadata = CreateEventMetadata(); this.context.Tracer.RelatedError(metadata, "AcquireIndexLockAndOpenForWrites: Can't open the index because it doesn't exist"); return FileSystemTaskResult.FatalError; } this.projectionParseComplete.Wait(); FileSystemTaskResult result = FileSystemTaskResult.FatalError; try { this.indexFileStream = new FileStream(this.indexPath, FileMode.Open, FileAccess.Read, FileShare.Read, IndexFileStreamBufferSize); result = FileSystemTaskResult.Success; } catch (IOException e) { EventMetadata metadata = CreateEventMetadata(e); this.context.Tracer.RelatedWarning(metadata, "IOException in AcquireIndexLockAndOpenForWrites (Retryable)"); result = FileSystemTaskResult.RetryableError; } catch (Exception e) { EventMetadata metadata = CreateEventMetadata(e); this.context.Tracer.RelatedError(metadata, "Exception in AcquireIndexLockAndOpenForWrites (FatalError)"); result = FileSystemTaskResult.FatalError; } return result; }
开发者ID:microsoft,项目名称:VFSForGit,代码行数:35,代码来源:GitIndexProjection.cs
在OpenIndexForRead()方法中,File的代码示例类中的Open的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞
File.Open的代码示例7 - SignIndex()
using System.IO; private void SignIndex() { using (ITracer activity = this.tracer.StartActivity("SignIndex", EventLevel.Informational, Keywords.Telemetry, metadata: null)) { using (FileStream fs = File.Open(this.indexPath, FileMode.Open, FileAccess.ReadWrite)) { // Truncate the old hash off. The Index class is expected to preserve any existing hash. fs.SetLength(fs.Length - 20); using (HashingStream hashStream = new HashingStream(fs)) { fs.Position = 0; hashStream.CopyTo(Stream.Null); byte[] hash = hashStream.Hash; // The fs pointer is now where the old hash used to be. Perfect. :) fs.Write(hash, 0, hash.Length); } } } }
开发者ID:microsoft,项目名称:VFSForGit,代码行数:22,代码来源:Index.cs
在SignIndex()方法中,File的代码示例类中的Open的代码示例方法一共出现了2次, 见黄色背景高亮显示的地方,欢迎大家点赞
File.Open的代码示例8 - ModifiedPathsFromChangesInsideRepoSavedAfterRemount()
using System.IO; [TestCaseSource(typeof(FileSystemRunner), nameof(FileSystemRunner.Runners))] public void ModifiedPathsFromChangesInsideRepoSavedAfterRemount(FileSystemRunner fileSystem) { string[] expectedModifiedFilesContentsAfterRemount = { @"A .gitattributes", $"A {GVFSHelpers.ConvertPathToGitFormat(FileToAdd)}", $"A {GVFSHelpers.ConvertPathToGitFormat(FileToUpdate)}", $"A {FileToDelete}", $"A {GVFSHelpers.ConvertPathToGitFormat(FileToRename)}", $"A {GVFSHelpers.ConvertPathToGitFormat(RenameFileTarget)}", $"A {FolderToCreate}/", $"A {RenameNewDotGitFileTarget}", $"A {FolderToDelete}/", }; string fileToAdd = this.Enlistment.GetVirtualPathTo(FileToAdd); fileSystem.WriteAllText(fileToAdd, "Contents for the new file"); string fileToUpdate = this.Enlistment.GetVirtualPathTo(FileToUpdate); fileSystem.AppendAllText(fileToUpdate, "// Testing"); string fileToDelete = this.Enlistment.GetVirtualPathTo(FileToDelete); fileSystem.DeleteFile(fileToDelete); fileToDelete.ShouldNotExistOnDisk(fileSystem); string fileToRename = this.Enlistment.GetVirtualPathTo(FileToRename); fileSystem.MoveFile(fileToRename, this.Enlistment.GetVirtualPathTo(RenameFileTarget)); string folderToCreate = this.Enlistment.GetVirtualPathTo(FolderToCreate); fileSystem.CreateDirectory(folderToCreate); string folderToRename = this.Enlistment.GetVirtualPathTo(FolderToRename); fileSystem.CreateDirectory(folderToRename); string folderToRenameTarget = this.Enlistment.GetVirtualPathTo(RenameFolderTarget); fileSystem.MoveDirectory(folderToRename, folderToRenameTarget); // Deleting the new folder will remove it from the modified paths file fileSystem.DeleteDirectory(folderToRenameTarget); folderToRenameTarget.ShouldNotExistOnDisk(fileSystem); // Moving a file from the .git folder to the working directory should add the file to the modified paths string dotGitfileToAdd = this.Enlistment.GetVirtualPathTo(DotGitFileToCreate); fileSystem.WriteAllText(dotGitfileToAdd, "Contents for the new file in dot git"); fileSystem.MoveFile(dotGitfileToAdd, this.Enlistment.GetVirtualPathTo(RenameNewDotGitFileTarget)); string folderToDeleteFullPath = this.Enlistment.GetVirtualPathTo(FolderToDelete); fileSystem.WriteAllText(Path.Combine(folderToDeleteFullPath, "NewFile.txt"), "Contents for new file"); string newFileToDelete = Path.Combine(folderToDeleteFullPath, "NewFileToDelete.txt"); fileSystem.WriteAllText(newFileToDelete, "Contents for new file"); fileSystem.DeleteFile(newFileToDelete); fileSystem.WriteAllText(Path.Combine(folderToDeleteFullPath, "CreateCommonVersionHeader.bat"), "Changing the file contents"); fileSystem.DeleteFile(Path.Combine(folderToDeleteFullPath, "RunUnitTests.bat")); fileSystem.DeleteDirectory(folderToDeleteFullPath); folderToDeleteFullPath.ShouldNotExistOnDisk(fileSystem); // Remount this.Enlistment.UnmountGVFS(); this.Enlistment.MountGVFS(); this.Enlistment.WaitForBackgroundOperations(); string modifiedPathsDatabase = Path.Combine(this.Enlistment.DotGVFSRoot, TestConstants.Databases.ModifiedPaths); modifiedPathsDatabase.ShouldBeAFile(fileSystem); using (StreamReader reader = new StreamReader(File.Open(modifiedPathsDatabase, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))) { reader.ReadToEnd().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).OrderBy(x => x) .ShouldMatchInOrder(expectedModifiedFilesContentsAfterRemount.OrderBy(x => x)); } }
开发者ID:microsoft,项目名称:VFSForGit,代码行数:73,代码来源:ModifiedPathsTests.cs
在ModifiedPathsFromChangesInsideRepoSavedAfterRemount()方法中,File的代码示例类中的Open的代码示例方法一共出现了2次, 见黄色背景高亮显示的地方,欢迎大家点赞
本文中的File.Open方法示例由csref.cn整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。