📜  C#中的File.AppendText()方法与示例

📅  最后修改于: 2021-05-30 01:11:08             🧑  作者: Mango

File.AppendText()是一个内置的File类方法,该方法用于创建StreamWriter,该StreamWriter将UTF-8编码的文本附加到现有文件中;否则,如果指定的文件不存在,它将创建一个新文件。

句法:

public static System.IO.StreamWriter AppendText (string path);

参数:该函数接受如下所示的参数:

例外情况

  • UnauthorizedAccessException:调用者没有所需的权限。
  • ArgumentException:路径是长度为零的字符串,仅包含空格,或包含一个或多个InvalidPathChars定义的无效字符。
  • ArgumentNullException:路径为null。
  • PathTooLongException:给定的路径,文件名或两者都超过了系统定义的最大长度。
  • DirectoryNotFoundException:给定的路径无效,即目录不存在或在未映射的驱动器上。
  • NotSupportedException:路径格式无效。

返回值:返回将指定的UTF-8编码文本附加到指定文件或新文件的流编写器。

下面是说明File.AppendText()方法的程序。

程序1:在运行下面的代码之前,将创建一个文件file.txt ,其中包含一些内容,如下所示:

file.txt

// C# program to illustrate the usage
// of File.AppendText() method
  
// Using System, System.IO namespaces
using System;
using System.IO;
  
class GFG {
    // Main method
    public static void Main()
    {
        // Creating a file
        string myfile = @"file.txt";
  
        // Appending the given texts
        using(StreamWriter sw = File.AppendText(myfile))
        {
            sw.WriteLine("Gfg");
            sw.WriteLine("GFG");
            sw.WriteLine("GeeksforGeeks");
        }
  
        // Opening the file for reading
        using(StreamReader sr = File.OpenText(myfile))
        {
            string s = "";
            while ((s = sr.ReadLine()) != null) {
                Console.WriteLine(s);
            }
        }
    }
}

执行中:

mcs -out:main.exe main.cs
mono main.exe
Geeks
Gfg
GFG
GeeksforGeeks

运行以上代码后,将显示以上输出,并且现有文件file.txt如下所示:

程序2:最初没有创建任何文件,因此下面的代码本身创建了一个名为file.txt的文件

// C# program to illustrate the usage
// of File.AppendText() method
  
// Using System, System.IO namespaces
using System;
using System.IO;
  
class GFG {
    // Main method
    public static void Main()
    {
        // Creating a file
        string myfile = @"file.txt";
  
        // Checking the above file
        if (!File.Exists(myfile)) {
            // Creating the same file if it doesn't exist
            using(StreamWriter sw = File.CreateText(myfile))
            {
                sw.WriteLine("GeeksforGeeks");
                sw.WriteLine("is");
                sw.WriteLine("a");
            }
        }
  
        // Appending the given texts
        using(StreamWriter sw = File.AppendText(myfile))
        {
            sw.WriteLine("computer");
            sw.WriteLine("science");
            sw.WriteLine("portal.");
        }
  
        // Opening the file for reading
        using(StreamReader sr = File.OpenText(myfile))
        {
            string s = "";
            while ((s = sr.ReadLine()) != null) {
                Console.WriteLine(s);
            }
        }
    }
}

执行中:

mcs -out:main.exe main.cs
mono main.exe
GeeksforGeeks
is
a
computer
science
portal.

运行上面的代码后,将创建一个新文件file.txt ,如下所示:

file.txt