C# File.CreateText实例讲解

发布时间:2025-12-09 11:57:37 浏览次数:1

File.CreateText()是内置的File类方法,用于用给定的UTF-8编码文本覆盖现有文件的内容,如果尚未创建文件,则此函数将创建具有指定内容的新文件。

用法:

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

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



  • Path: This is the file where UTF-8 encoded texts are going to be overwritten. The file is created if it doesn’t already exist.

异常:

  • UnauthorizedAccessException:调用者没有所需的权限。或路径指定了只读文件。或路径指定了隐藏的文件。
  • ArgumentException:路径是长度为零的字符串,仅包含空格或一个或多个无效字符。
  • ArgumentNullException:路径为空。
  • PathTooLongException:指定的路径,文件名或两者都超过了system-defined的最大长度。
  • DirectoryNotFoundException:指定的路径无效,即它位于未映射的驱动器上。
  • NotSupportedException:路径格式无效。

返回值:返回使用UTF-8编码写入指定文件的StreamWriter。

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

程序1:

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

// C# program to illustrate the usage // of File.CreateText() 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";           // Overwriting to the above existing file         using(StreamWriter sw = File.CreateText(myfile))         {             sw.WriteLine("GeeksforGeeks");             sw.WriteLine("is a");             sw.WriteLine("computer 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.csmono main.exeGeeksforGeeksis acomputer scienceportal.

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

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

// C# program to illustrate the usage // of File.CreateText() 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 existance of above file         if (!File.Exists(myfile)) {             // Creating a new file with below contents             using(StreamWriter sw = File.CreateText(myfile))             {                 sw.WriteLine("Geeks");                 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.csmono main.exeGeeksGFGGeeksforGeeks

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




createtextfile
需要做网站?需要网络推广?欢迎咨询客户经理 13272073477