C# StreamWriter.Write的代码示例

通过代码示例来学习C# StreamWriter.Write方法

通过代码示例来学习编程是非常高效的。
1. 代码示例提供了一个具体而直观的学习环境,使初学者能够立即看到编程概念和语法的实际应用。
2. 通过分析和模仿现有的代码实例,初学者可以更好地理解编程逻辑和算法的工作原理。
3. 代码实例往往涵盖了多种编程技巧和最佳实践,通过学习和模仿这些实例,学习者可以逐步掌握如何编写高效、可读性强和可维护的代码。这对于初学者来说,是一种快速提升编程水平的有效途径。


StreamWriter.Write是C#的System.IO命名空间下中的一个方法, 小编为大家找了一些网络大拿们常见的代码示例,源码中的StreamWriter.Write() 已经帮大家高亮显示了,大家可以重点学习StreamWriter.Write() 方法的写法,从而快速掌握该方法的应用。

StreamWriter.Write的代码示例1 - CreateHeaderFooterPackage()

    using System.IO;

    private void CreateHeaderFooterPackage( string element, string reference, int index, XElement sectPr, int headerType )
    {
      var header_uri = string.Format( "/word/{0}{1}.xml", reference, index );

      var headerPart = this.Document._package.CreatePart( new Uri( header_uri, UriKind.Relative ), string.Format( "application/vnd.openxmlformats-officedocument.wordprocessingml.{0}+xml", reference ), CompressionOption.Normal );
      var headerRelationship = this.Document.PackagePart.CreateRelationship( headerPart.Uri, TargetMode.Internal, string.Format( "http://schemas.openxmlformats.org/officeDocument/2006/relationships/{0}", reference ) );

      XDocument header;

      // Load the document part into a XDocument object
      using( TextReader tr = new StreamReader( headerPart.GetStream( FileMode.Create, FileAccess.ReadWrite ) ) )
      {
        header = XDocument.Parse
        ( string.Format( @"
                       
                         
                           
                             
                           
                         
                       ", element, reference )
        );
      }

      // Save the main document
      using( TextWriter tw = new StreamWriter( new PackagePartStream( headerPart.GetStream( FileMode.Create, FileAccess.Write ) ) ) )
      {
        header.Save( tw, SaveOptions.None );
      }

      string type;
      switch( headerType )
      {
        case 0:
          type = "default";
          break;
        case 1:
          type = "even";
          break;
        case 2:
          type = "first";
          break;
        default:
          throw new ArgumentOutOfRangeException();
      }

      sectPr.Add
      (
          new XElement
          (
              w + string.Format( "{0}Reference", reference ),
              new XAttribute( w + "type", type ),
              new XAttribute( r + "id", headerRelationship.Id )
          )
      );
    }
    

开发者ID:xceedsoftware,项目名称:DocX,代码行数:58,代码来源:Section.cs

在CreateHeaderFooterPackage()方法中,StreamWriter的代码示例类中的Write的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

StreamWriter.Write的代码示例2 - AppendToNewlineSeparatedFile()

    using System.IO;

        public static void AppendToNewlineSeparatedFile(PhysicalFileSystem fileSystem, string filename, string newContent)
        {
            using (Stream fileStream = fileSystem.OpenFileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite, false))
            {
                using (StreamReader reader = new StreamReader(fileStream))
                using (StreamWriter writer = new StreamWriter(fileStream))
                {
                    long position = reader.BaseStream.Seek(0, SeekOrigin.End);
                    if (position > 0)
                    {
                        reader.BaseStream.Seek(position - 1, SeekOrigin.Begin);
                    }

                    string lastCharacter = reader.ReadToEnd();
                    if (lastCharacter != "\n" && lastCharacter != string.Empty)
                    {
                        writer.Write("\n");
                    }

                    writer.Write(newContent.Trim());
                    writer.Write("\n");
                }

                fileStream.Close();
            }
        }
    

开发者ID:microsoft,项目名称:VFSForGit,代码行数:28,代码来源:BlobPrefetcher.cs

在AppendToNewlineSeparatedFile()方法中,StreamWriter的代码示例类中的Write的代码示例方法一共出现了3次, 见黄色背景高亮显示的地方,欢迎大家点赞

StreamWriter.Write的代码示例3 - CreateGitScript()

    using System.IO;

        // TODO(#1364): Don't call this method on POSIX platforms (or have it no-op on them)
        private void CreateGitScript(GVFSEnlistment enlistment)
        {
            FileInfo gitCmd = new FileInfo(Path.Combine(enlistment.EnlistmentRoot, "git.cmd"));
            using (FileStream fs = gitCmd.Create())
            using (StreamWriter writer = new StreamWriter(fs))
            {
                writer.Write(
@"
@echo OFF
echo .
echo ^
echo      This repo was cloned using GVFS, and the git repo is in the 'src' directory
echo      Switching you to the 'src' directory and rerunning your git command
echo                                                                                      

@echo ON
cd src
git %*
");
            }

            gitCmd.Attributes = FileAttributes.Hidden;
        }
    

开发者ID:microsoft,项目名称:VFSForGit,代码行数:26,代码来源:CloneVerb.cs

在CreateGitScript()方法中,StreamWriter的代码示例类中的Write的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

StreamWriter.Write的代码示例4 - TryWriteTempFile()

    using System.IO;

        /// 
        /// Attempts to write all data lines to tmp file
        /// 
        /// Method that returns the dataLines to write as an IEnumerable
        /// Output parameter that's set when TryWriteTempFile catches a non-fatal exception
        /// True if the write succeeded and false otherwise
        /// If a fatal exception is encountered while trying to write the temp file, this method will not catch it.
        private bool TryWriteTempFile(Func> getDataLines, out Exception handledException)
        {
            handledException = null;

            try
            {
                using (Stream tempFile = this.fileSystem.OpenFileStream(this.tempFilePath, FileMode.Create, FileAccess.Write, FileShare.None, callFlushFileBuffers: true))
                using (StreamWriter writer = new StreamWriter(tempFile))
                {
                    foreach (string line in getDataLines())
                    {
                        writer.Write(line + NewLine);
                    }

                    tempFile.Flush();
                }

                return true;
            }
            catch (IOException e)
            {
                handledException = e;
                return false;
            }
            catch (UnauthorizedAccessException e)
            {
                handledException = e;
                return false;
            }
        }
    

开发者ID:microsoft,项目名称:VFSForGit,代码行数:39,代码来源:FileBasedCollection.cs

在TryWriteTempFile()方法中,StreamWriter的代码示例类中的Write的代码示例方法一共出现了2次, 见黄色背景高亮显示的地方,欢迎大家点赞

StreamWriter.Write的代码示例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()方法中,StreamWriter的代码示例类中的Write的代码示例方法一共出现了2次, 见黄色背景高亮显示的地方,欢迎大家点赞

StreamWriter.Write的代码示例6 - WriteLooseObjectIds()

    using System.IO;

        /// 
        /// Writes loose object Ids to streamWriter
        /// 
        /// Writer to which SHAs are written
        /// The number of loose objects SHAs written to the stream
        public int WriteLooseObjectIds(StreamWriter streamWriter)
        {
            int count = 0;

            foreach (string objectId in this.GetBatchOfLooseObjects(this.MaxLooseObjectsInPack))
            {
                streamWriter.Write(objectId + "\n");
                count++;
            }

            return count;
        }
    

开发者ID:microsoft,项目名称:VFSForGit,代码行数:19,代码来源:LooseObjectsStep.cs

在WriteLooseObjectIds()方法中,StreamWriter的代码示例类中的Write的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

StreamWriter.Write的代码示例7 - TryWriteTempFileAndRename()

    using System.IO;

        public bool TryWriteTempFileAndRename(string destinationPath, string contents, out Exception handledException)
        {
            handledException = null;
            string tempFilePath = destinationPath + ".temp";

            string parentPath = Path.GetDirectoryName(tempFilePath);
            this.CreateDirectory(parentPath);

            try
            {
                using (Stream tempFile = this.OpenFileStream(tempFilePath, FileMode.Create, FileAccess.Write, FileShare.None, callFlushFileBuffers: true))
                using (StreamWriter writer = new StreamWriter(tempFile))
                {
                    writer.Write(contents);
                    tempFile.Flush();
                }

                this.MoveAndOverwriteFile(tempFilePath, destinationPath);
                return true;
            }
            catch (Win32Exception e)
            {
                handledException = e;
                return false;
            }
            catch (IOException e)
            {
                handledException = e;
                return false;
            }
            catch (UnauthorizedAccessException e)
            {
                handledException = e;
                return false;
            }
        }
    

开发者ID:microsoft,项目名称:VFSForGit,代码行数:38,代码来源:PhysicalFileSystem.cs

在TryWriteTempFileAndRename()方法中,StreamWriter的代码示例类中的Write的代码示例方法一共出现了2次, 见黄色背景高亮显示的地方,欢迎大家点赞

StreamWriter.Write的代码示例8 - WriteRegistry()

    using System.IO;

        private void WriteRegistry(Dictionary registry)
        {
            string tempFilePath = Path.Combine(this.registryParentFolderPath, RegistryTempName);
            using (Stream stream = this.fileSystem.OpenFileStream(
                    tempFilePath,
                    FileMode.Create,
                    FileAccess.Write,
                    FileShare.None,
                    callFlushFileBuffers: true))
            using (StreamWriter writer = new StreamWriter(stream))
            {
                writer.WriteLine(RegistryVersion);

                foreach (RepoRegistration repo in registry.Values)
                {
                    writer.WriteLine(repo.ToJson());
                }

                stream.Flush();
            }

            this.fileSystem.MoveAndOverwriteFile(tempFilePath, Path.Combine(this.registryParentFolderPath, RegistryName));
        }
    

开发者ID:microsoft,项目名称:VFSForGit,代码行数:25,代码来源:RepoRegistry.cs

在WriteRegistry()方法中,StreamWriter的代码示例类中的Write的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

本文中的StreamWriter.Write方法示例由csref.cn整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。