C# File.Write的代码示例
通过代码示例来学习C# File.Write方法
通过代码示例来学习编程是非常高效的。
1. 代码示例提供了一个具体而直观的学习环境,使初学者能够立即看到编程概念和语法的实际应用。
2. 通过分析和模仿现有的代码实例,初学者可以更好地理解编程逻辑和算法的工作原理。
3. 代码实例往往涵盖了多种编程技巧和最佳实践,通过学习和模仿这些实例,学习者可以逐步掌握如何编写高效、可读性强和可维护的代码。这对于初学者来说,是一种快速提升编程水平的有效途径。
File.Write是C#的System.IO命名空间下中的一个方法, 小编为大家找了一些网络大拿们常见的代码示例,源码中的File.Write() 已经帮大家高亮显示了,大家可以重点学习File.Write() 方法的写法,从而快速掌握该方法的应用。
File.Write的代码示例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的代码示例类中的Write的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞
File.Write的代码示例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的代码示例类中的Write的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞
File.Write的代码示例3 - 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的代码示例类中的Write的代码示例方法一共出现了2次, 见黄色背景高亮显示的地方,欢迎大家点赞
File.Write的代码示例4 - WriteLooseObject_Success()
using System.IO; [TestCase] public void WriteLooseObject_Success() { ITracer tracer = new MockTracer(); GVFSEnlistment enlistment = new MockGVFSEnlistment(); MockFileSystemWithCallbacks filesystem = new MockFileSystemWithCallbacks(); GVFSContext context = new GVFSContext(tracer, filesystem, null, enlistment); GitObjects gitObjects = new GVFSGitObjects(context, null); this.openedPaths.Clear(); filesystem.OnOpenFileStream = this.OnOpenFileStream; filesystem.OnFileExists = this.OnFileExists; bool moved = false; filesystem.OnMoveFile = (path1, path2) => { moved = true; }; using (Stream stream = new MemoryStream()) { stream.Write(this.realData, 0, this.realData.Length); stream.Position = 0; gitObjects.WriteLooseObject(stream, RealSha, true, new byte[128]); } this.openedPaths.Count.ShouldEqual(2, "Incorrect number of opened paths"); moved.ShouldBeTrue("File was not moved"); }
开发者ID:microsoft,项目名称:VFSForGit,代码行数:29,代码来源:GitObjectsTests.cs
在WriteLooseObject_Success()方法中,File的代码示例类中的Write的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞
File.Write的代码示例5 - 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的代码示例类中的Write的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞
File.Write的代码示例6 - OpenForWrite()
using System.IO; private static SafeFileHandle OpenForWrite(ITracer tracer, string fileName) { SafeFileHandle handle = CreateFile(fileName, FileAccess.Write, FileShare.None, IntPtr.Zero, FileMode.Create, FileAttributes.Normal, IntPtr.Zero); if (handle.IsInvalid) { // If we get a access denied, try reverting the acls to defaults inherited by parent if (Marshal.GetLastWin32Error() == AccessDeniedWin32Error) { tracer.RelatedEvent( EventLevel.Warning, "FailedOpenForWrite", new EventMetadata { { TracingConstants.MessageKey.WarningMessage, "Received access denied. Attempting to delete." }, { "FileName", fileName } }); File.SetAttributes(fileName, FileAttributes.Normal); File.Delete(fileName); handle = CreateFile(fileName, FileAccess.Write, FileShare.None, IntPtr.Zero, FileMode.Create, FileAttributes.Normal, IntPtr.Zero); } } return handle; }
开发者ID:microsoft,项目名称:VFSForGit,代码行数:28,代码来源:NativeMethods.cs
在OpenForWrite()方法中,File的代码示例类中的Write的代码示例方法一共出现了2次, 见黄色背景高亮显示的地方,欢迎大家点赞
File.Write的代码示例7 - BuildCmd()
using System.IO; ///
/// Builds the WiX source file and generates batch file capable of building /// WiX/MSI bootstrapper with WiX toolset. /// /// The project. /// The path to the batch file to be created. ///Wix compiler/linker cannot be found public static string BuildCmd(Bundle project, string path = null) { if (path == null) path = IO.Path.GetFullPath(IO.Path.Combine(project.OutDir, "Build_" + project.OutFileName) + ".cmd"); path = path.ExpandEnvVars(); //System.Diagnostics.Debug.Assert(false); string wixLocationEnvVar = $"set WixLocation={WixLocation}" + Environment.NewLine; string compiler = Utils.PathCombine(WixLocation, "candle.exe"); string linker = Utils.PathCombine(WixLocation, "light.exe"); string batchFile = path; if (!IO.File.Exists(compiler) || !IO.File.Exists(linker)) { Compiler.OutputWriteLine("Wix binaries cannot be found. Expected location is " + IO.Path.GetDirectoryName(compiler)); throw new ApplicationException("Wix compiler/linker cannot be found"); } else { string wxsFile = BuildWxs(project); if (!project.SourceBaseDir.IsEmpty()) Environment.CurrentDirectory = project.SourceBaseDir; string objFile = IO.Path.ChangeExtension(wxsFile, ".wixobj"); string pdbFile = IO.Path.ChangeExtension(wxsFile, ".wixpdb"); string extensionDlls = ""; // note we need to avoid possible duplications cause by non expanded envars // %wix_location%\ext.dll vs c:\Program Files\...\ext.dll foreach (string dll in project.WixExtensions.DistinctBy(x => x.ExpandEnvVars())) extensionDlls += " -ext \"" + dll + "\""; string wxsFiles = ""; foreach (string file in project.WxsFiles.Distinct()) wxsFiles += " \"" + file + "\""; var candleOptions = CandleOptions + " " + project.CandleOptions; string batchFileContent = wixLocationEnvVar + "\"" + compiler + "\" " + candleOptions + " " + extensionDlls + " \"" + wxsFile + "\" "; string outDir = null; if (wxsFiles.IsNotEmpty()) { batchFileContent += wxsFiles; outDir = IO.Path.GetDirectoryName(wxsFile); // if multiple files are specified candle expect a path for the -out switch // or no path at all (use current directory) // note the '\' character must be escaped twice: as a C# string and as a CMD char if (outDir.IsNotEmpty()) batchFileContent += $" -out \"{outDir}\\\\\""; } else batchFileContent += $" -out \"{objFile}\""; batchFileContent += "\r\n"; string fragmentObjectFiles = project.WxsFiles .Distinct() .JoinBy(" ", file => "\"" + outDir.PathCombine(IO.Path.GetFileNameWithoutExtension(file)) + ".wixobj\""); string lightOptions = LightOptions + " " + project.LightOptions; if (fragmentObjectFiles.IsNotEmpty()) lightOptions += " " + fragmentObjectFiles; if (path.IsNotEmpty()) lightOptions += " -out \"" + IO.Path.ChangeExtension(objFile, ".exe") + "\""; batchFileContent += "\"" + linker + "\" " + lightOptions + " \"" + objFile + "\" " + extensionDlls + " -cultures:" + project.Language + "\r\npause"; batchFileContent = batchFileContent.ExpandEnvVars(); using (var sw = new IO.StreamWriter(batchFile)) sw.Write(batchFileContent); } return path; }
开发者ID:oleg-shilo,项目名称:wixsharp,代码行数:90,代码来源:Compiler.Bootstrapper.cs
在BuildCmd()方法中,File的代码示例类中的Write的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞
File.Write的代码示例8 - Save()
using System.IO; // Mostly everything from this point was imported from: // https://github.com/Jenrikku/NARCSharp public void Save(Stream stream) { using(BinaryDataWriter writer = new BinaryDataWriter(stream)) { #region Header writer.Write("NARC", BinaryStringFormat.NoPrefixOrTermination, Encoding.ASCII); // Magic. writer.ByteOrder = (ByteOrder) header.ByteOrder; writer.Write((ushort) 0xFFFE); // ByteOrder. writer.Write(header.Version); // Version. long headerLengthPorsition = writer.Position; writer.Position += 4; // Skips length writing. writer.Write(header.HeaderSize); // Header length. writer.Write(header.DataBlocks); // Section count. #endregion #region BTAF preparation long btafPosition = WriteSectionHeader("BTAF"); // Header. writer.Write((uint) files.Count); // File count. for(uint i = 0; i < files.Count; i++) // Reads unset bytes per file. (Reserved space for later) writer.Position += 8; WriteSectionLength(btafPosition); #endregion #region BTNF long btnfPosition = WriteSectionHeader("BTNF"); // Header. writer.Write(bfntUnk.Length + 4); writer.Write(bfntUnk); foreach(ArchiveFileInfo file in files) writer.Write(file.FileName, BinaryStringFormat.ByteLengthPrefix); writer.Write((byte) 0x00); writer.Align(128); WriteSectionLength(btnfPosition); #endregion #region GMIF long gmifPosition = WriteSectionHeader("GMIF"); // Header. long btafCurrentPosition = btafPosition + 12; // First offset-size position. (BTAF) foreach(ArchiveFileInfo file in files) { WriteBTAFEntry(); // BTAF offset writer.Write(file.FileData); WriteBTAFEntry(); // BTAF size. writer.Align(128); } WriteSectionLength(gmifPosition); #endregion writer.Position = headerLengthPorsition; writer.Write((uint) writer.BaseStream.Length); // Total file length. long WriteSectionHeader(string magic) { long startPosition = writer.Position; writer.Write(magic, BinaryStringFormat.NoPrefixOrTermination, Encoding.ASCII); // Magic. writer.Position += 4; // Skips length position. return startPosition; } void WriteSectionLength(long startPosition) { using(writer.TemporarySeek()) { long finalLength = (uint) writer.Position; writer.Position = startPosition + 4; writer.Write((uint) (finalLength - startPosition)); } } void WriteBTAFEntry() { uint value = (uint) (writer.Position - (gmifPosition + 8)); using(writer.TemporarySeek()) { writer.Position = btafCurrentPosition; writer.Write(value); } btafCurrentPosition += 4; } } }
开发者ID:KillzXGaming,项目名称:Switch-Toolbox,代码行数:92,代码来源:NARC.cs
在Save()方法中,File的代码示例类中的Write的代码示例方法一共出现了15次, 见黄色背景高亮显示的地方,欢迎大家点赞
本文中的File.Write方法示例由csref.cn整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。