C#基础 File AppendAllText 追加 在原有内容后,添加string中的内容

    xiaoxiao2022-07-14  148

    .NET Framework : 4.7.2       IDE : Visual Studio Community 2019        OS : Windows 10 x64    typesetting : Markdown        blog : blog.csdn.net/yushaopu       github : github.com/GratefulHeartCoder

    txt file - 未运行程序

    道德经-第八章 上善若水。 水善利万物而不争,处众人之所恶,故几于道。 居善地;心善渊;与善仁;言善信;政善治;事善能;动善时。 夫唯不争,故无尤。

    code

    using System; using System.IO; namespace ConsoleApp { class Program { static void Main(string[] args) { string path = "TaoTeChing-utf8.txt"; string contents = "道德经 - 第十五章\r\n古之善为士者,微妙玄通,深不可识。夫惟不可识,故强为之容。\r\n豫兮若冬涉川,犹兮若畏四邻,俨兮其若客,涣兮若冰之将释,孰兮其若朴,旷兮其若谷,浑兮其若浊。\r\n孰能浊以澄静之徐清?孰能安以久动之徐生?保此道者不欲盈,夫惟不盈,故能敝不新成。"; File.AppendAllText(path, contents); Console.WriteLine("OK"); Console.ReadKey(); } } }

    result

    OK

    txt file - 运行程序后

    道德经-第八章 上善若水。 水善利万物而不争,处众人之所恶,故几于道。 居善地;心善渊;与善仁;言善信;政善治;事善能;动善时。 夫唯不争,故无尤。 道德经 - 第十五章 古之善为士者,微妙玄通,深不可识。夫惟不可识,故强为之容。 豫兮若冬涉川,犹兮若畏四邻,俨兮其若客,涣兮若冰之将释,孰兮其若朴,旷兮其若谷,浑兮其若浊。 孰能浊以澄静之徐清?孰能安以久动之徐生?保此道者不欲盈,夫惟不盈,故能敝不新成。

    more knowledge

    注意看string中,加的是\n还是\r\n? 两者有什么区别?在Linux、Windows、Mac系统中具体用哪个? 有空时,可以详细了解一下。

    关于 File.AppendAllText 如何释放资源的问题,可以查看相关的源代码来做简单了解 网址:https://referencesource.microsoft.com/#mscorlib/system/io/file.cs,4ff1446b33bdfb6b 两个关键的代码段

    [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public static void AppendAllText(String path, String contents) { if (path == null) throw new ArgumentNullException("path"); if (path.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath")); Contract.EndContractBlock(); InternalAppendAllText(path, contents, StreamWriter.UTF8NoBOM); } [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] private static void InternalAppendAllText(String path, String contents, Encoding encoding) { Contract.Requires(path != null); Contract.Requires(encoding != null); Contract.Requires(path.Length > 0); using (StreamWriter sw = new StreamWriter(path, true, encoding)) sw.Write(contents); }

    resource

    [文档] docs.microsoft.com/zh-cn/dotnet/csharp[规范] github.com/dotnet/docs/tree/master/docs/standard/design-guidelines[源码] referencesource.microsoft.com [平台] www.csdn.net[ IDE ] visualstudio.microsoft.com/zh-hans[.NET Core] dotnet.github.io


    感恩曾经帮助过 心少朴 的人。 C#优秀,值得学习。.NET Core具有跨平台的能力,值得关注。 Console,WinForm,WPF,ASP.NET,Azure WebJob,WCF,Unity3d,UWP可以适当地了解。 注:此文是自学笔记所生,质量中下等,故要三思而后行。新手到此,不可照搬,应先研究其理象数,待能变通之时,自然跳出深坑。

    最新回复(0)