C# File.AppendAllText的代码示例

通过代码示例来学习C# File.AppendAllText方法

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


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

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

File.AppendAllText的代码示例2 - CanReadWriteAFileInParallel()

    using System.IO;

        [TestCaseSource(typeof(FileSystemRunner), nameof(FileSystemRunner.Runners))]
        [Order(3)]
        public void CanReadWriteAFileInParallel(FileSystemRunner fileSystem)
        {
            string fileName = @"CanReadWriteAFileInParallel";
            string virtualPath = this.Enlistment.GetVirtualPathTo(fileName);

            // Create the file new each time.
            virtualPath.ShouldNotExistOnDisk(fileSystem);
            File.Create(virtualPath).Dispose();

            bool keepRunning = true;
            Thread[] threads = new Thread[4];
            StringBuilder[] fileContents = new StringBuilder[4];

            // Writer
            fileContents[0] = new StringBuilder();
            threads[0] = new Thread(() =>
            {
                DateTime start = DateTime.Now;
                Random r = new Random(0); // Seeded for repeatability
                while ((DateTime.Now - start).TotalSeconds < 2.5)
                {
                    string newChar = r.Next(10).ToString();
                    fileSystem.AppendAllText(virtualPath, newChar);
                    fileContents[0].Append(newChar);
                    Thread.Yield();
                }

                keepRunning = false;
            });

            // Readers
            for (int i = 1; i < threads.Length; ++i)
            {
                int myIndex = i;
                fileContents[i] = new StringBuilder();
                threads[i] = new Thread(() =>
                {
                    using (Stream readStream = File.Open(virtualPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    using (StreamReader reader = new StreamReader(readStream, true))
                    {
                        while (keepRunning)
                        {
                            Thread.Yield();
                            fileContents[myIndex].Append(reader.ReadToEnd());
                        }

                        // Catch the last write that might have escaped us
                        fileContents[myIndex].Append(reader.ReadToEnd());
                    }
                });
            }

            foreach (Thread thread in threads)
            {
                thread.Start();
            }

            foreach (Thread thread in threads)
            {
                thread.Join();
            }

            for (int i = 1; i < threads.Length; ++i)
            {
                fileContents[i].ToString().ShouldEqual(fileContents[0].ToString());
            }

            fileSystem.DeleteFile(virtualPath);
        }
    

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

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

File.AppendAllText的代码示例3 - Build_TouchesUpToDateMarkerFile()

    using System.IO;

        [Fact]
        [InitializeTestProject("ClassLibrary")]
        public async Task Build_TouchesUpToDateMarkerFile()
        {
            var classLibraryDll = Path.Combine(IntermediateOutputPath, "ClassLibrary.dll");
            var classLibraryViewsDll = Path.Combine(IntermediateOutputPath, "ClassLibrary.Views.dll");
            var markerFile = Path.Combine(IntermediateOutputPath, "ClassLibrary.csproj.CopyComplete");

            var result = await DotnetMSBuild("Build");
            Assert.BuildPassed(result);

            Assert.FileExists(result, classLibraryDll);
            Assert.FileExists(result, classLibraryViewsDll);
            Assert.FileExists(result, markerFile);

            // Gather thumbprints before incremental build.
            var classLibraryThumbPrint = GetThumbPrint(classLibraryDll);
            var classLibraryViewsThumbPrint = GetThumbPrint(classLibraryViewsDll);
            var markerFileThumbPrint = GetThumbPrint(markerFile);

            result = await DotnetMSBuild("Build");
            Assert.BuildPassed(result);

            // Verify thumbprint file is unchanged between true incremental builds
            Assert.Equal(classLibraryThumbPrint, GetThumbPrint(classLibraryDll));
            Assert.Equal(classLibraryViewsThumbPrint, GetThumbPrint(classLibraryViewsDll));
            // In practice, this should remain unchanged. However, since our tests reference
            // binaries from other projects, this file gets updated by Microsoft.Common.targets
            Assert.NotEqual(markerFileThumbPrint, GetThumbPrint(markerFile));

            // Change a cshtml file and verify ClassLibrary.Views.dll and marker file are updated
            File.AppendAllText(Path.Combine(Project.DirectoryPath, "Views", "_ViewImports.cshtml"), Environment.NewLine);

            result = await DotnetMSBuild("Build");
            Assert.BuildPassed(result);

            Assert.Equal(classLibraryThumbPrint, GetThumbPrint(classLibraryDll));
            Assert.NotEqual(classLibraryViewsThumbPrint, GetThumbPrint(classLibraryViewsDll));
            Assert.NotEqual(markerFileThumbPrint, GetThumbPrint(markerFile));
        }
    

开发者ID:aspnet,项目名称:Razor,代码行数:42,代码来源:BuildIncrementalismTest.cs

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

File.AppendAllText的代码示例4 - Build_WithP2P_WorksWhenBuildProjectReferencesIsDisabled()

    using System.IO;

        [Fact]
        [InitializeTestProject("AppWithP2PReference", additionalProjects: new[] { "ClassLibrary", "ClassLibrary2" })]
        public async Task Build_WithP2P_WorksWhenBuildProjectReferencesIsDisabled()
        {
            // Simulates building the same way VS does by setting BuildProjectReferences=false.
            // With this flag, P2P references aren't resolved during GetCopyToOutputDirectoryItems. This test ensures that
            // no Razor work is done in such a scenario and the build succeeds.
            var additionalProjectContent = @"

  

";
            AddProjectFileContent(additionalProjectContent);

            var result = await DotnetMSBuild(target: default);

            Assert.BuildPassed(result);

            Assert.FileExists(result, OutputPath, "AppWithP2PReference.dll");
            Assert.FileExists(result, OutputPath, "AppWithP2PReference.Views.dll");
            Assert.FileExists(result, OutputPath, "ClassLibrary.dll");
            Assert.FileExists(result, OutputPath, "ClassLibrary.Views.dll");
            Assert.FileExists(result, OutputPath, "ClassLibrary2.dll");
            Assert.FileExists(result, OutputPath, "ClassLibrary2.Views.dll");

            // Force a rebuild of ClassLibrary2 by changing a file
            var class2Path = Path.Combine(Project.SolutionPath, "ClassLibrary2", "Class2.cs");
            File.AppendAllText(class2Path, Environment.NewLine + "// Some changes");

            // dotnet msbuild /p:BuildProjectReferences=false
            result = await DotnetMSBuild(target: default, "/p:BuildProjectReferences=false", suppressRestore: true);

            Assert.BuildPassed(result);
        }
    

开发者ID:aspnet,项目名称:Razor,代码行数:36,代码来源:BuildIntegrationTest.cs

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

File.AppendAllText的代码示例5 - Log()

    using System.IO;

		public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter)
		{
			if (formatter is null)
				return;
			semaphoreSlim.Wait();

			try
			{
				var message = exception?.ToString() ?? formatter(state, exception);

				File.AppendAllText(filePath, $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.ffff}|{logLevel}|{message}" + Environment.NewLine);
			}
			catch (Exception e)
			{
				Debug.WriteLine($"Writing to log file failed with the following exception:\n{e}");
			}
			finally
			{
				semaphoreSlim.Release();
			}
		}
    

开发者ID:files-community,项目名称:Files,代码行数:23,代码来源:FileLogger.cs

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

File.AppendAllText的代码示例6 - ReportThread()

    using System.IO;

        private void ReportThread()
        {
            this.Timer.Start();

            var output = new StringBuilder();

            while(this.Timer.Elapsed < this.Duration && _running)
            {
                Thread.Sleep(Math.Min(1000, (int)this.Duration.Subtract(this.Timer.Elapsed).TotalMilliseconds));

                this.ReportPrint(output);

                Console.Clear();
                Console.WriteLine(output.ToString());
            }

            this.StopRunning();

            this.Timer.Stop();

            _db.Dispose();

            this.ReportPrint(output);
            this.ReportSummary(output);

            Console.Clear();
            Console.WriteLine(output.ToString());

            File.AppendAllText(_file.Output, output.ToString());
        }
    

开发者ID:mbdavid,项目名称:LiteDB,代码行数:32,代码来源:TestExecution.cs

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

File.AppendAllText的代码示例7 - ProcessMessageQueue()

    using System.IO;

        public void ProcessMessageQueue()
        {
            lock (loggerLock)
            {
                while (messageQueue.TryDequeue(out string message))
                {
                    if (DebugWrite)
                    {
                        Debug.Write(message);
                    }

                    if (StringWrite && sbMessages != null)
                    {
                        sbMessages.Append(message);
                    }

                    if (FileWrite && !string.IsNullOrEmpty(LogFilePath))
                    {
                        try
                        {
                            File.AppendAllText(LogFilePath, message, Encoding.UTF8);
                        }
                        catch (Exception e)
                        {
                            Debug.WriteLine(e);
                        }
                    }

                    OnMessageAdded(message);
                }
            }
        }
    

开发者ID:ShareX,项目名称:ShareX,代码行数:34,代码来源:Logger.cs

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

File.AppendAllText的代码示例8 - Restart()

    using System.IO;

        /// 重启服务
        /// 
        public void Restart(String reason)
        {
            WriteLog("重启服务!{0}", reason);

            // 在临时目录生成重启服务的批处理文件
            var filename = "重启.bat".GetFullPath();
            if (File.Exists(filename)) File.Delete(filename);

            File.AppendAllText(filename, "net stop " + ServiceName);
            File.AppendAllText(filename, Environment.NewLine);
            File.AppendAllText(filename, "ping 127.0.0.1 -n 5 > nul ");
            File.AppendAllText(filename, Environment.NewLine);
            File.AppendAllText(filename, "net start " + ServiceName);

            //执行重启服务的批处理
            //RunCmd(filename, false, false);
            var p = new Process();
            var si = new ProcessStartInfo
            {
                FileName = filename,
                UseShellExecute = true,
                CreateNoWindow = true
            };
            p.StartInfo = si;

            p.Start();

            //if (File.Exists(filename)) File.Delete(filename);
        }
    

开发者ID:NewLifeX,项目名称:X,代码行数:33,代码来源:ServiceBase.cs

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

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