当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C# File.WriteAllText(String, String)用法及代码示例


File.WriteAllText(String, String) 是一个内置的 File 类方法,用于创建一个新文件,将指定的字符串写入文件,然后关闭文件。如果目标文件已经存在,它会被覆盖。

用法:

public static void WriteAllText (string path, string contents);

参数:此函数接受两个参数,如下所示:

  • path: This is the specified file where specified string are going to be written.
  • contents: This is the specified string to write to the file.

异常:

  • ArgumentException:路径是一个长度为零的字符串,只包含空格,或者一个或多个由 InvalidPathChars 定义的无效字符。
  • ArgumentNullException:路径为空。
  • PathTooLongException:指定的路径,文件名或两者都超过了system-defined的最大长度。
  • DirectoryNotFoundException:指定的路径无效。
  • IOException:打开文件时发生I /O错误。
  • UnauthorizedAccessException:路径指定了一个只读文件。或者路径指定了一个隐藏的文件。 OR 当前平台不支持此操作。或者路径指定了一个目录。或者调用者没有所需的权限。
  • NotSupportedException:路径格式无效。
  • SecurityException:调用者没有所需的权限。

下面是说明 File.WriteAllText(String, String) 方法的程序。



程序1:最初,没有创建文件。下面的代码本身创建一个文件 file.txt 并将指定的字符串数组写入文件。


// C# program to illustrate the usage
// of File.WriteAllText(String, String) method
  
// Using System, System.IO and
// System.Text namespaces
using System;
using System.IO;
using System.Text;
  
class GFG {
    public static void Main()
    {
        // Specifying a file
        string path = @"file.txt";
  
        // Creating a string
        string createText = "GeeksforGeeks" + Environment.NewLine;
  
        // Writing the string to the file
        File.WriteAllText(path, createText);
  
        // Reading the contents of the file
        string readText = File.ReadAllText(path);
        Console.WriteLine(readText);
    }
}

输出:

GeeksforGeeks

运行上面的代码后,显示了上面的输出,并创建了一个新文件 file.txt 如下所示 -

file.txt

程序2:最初,创建了一个文件 file.txt,其中的一些内容如下所示-

file.txt

下面的代码用指定的字符串覆盖文件内容。


// C# program to illustrate the usage
// of File.WriteAllText(String, String) method
  
// Using System, System.IO and
// System.Text namespaces
using System;
using System.IO;
using System.Text;
  
class GFG {
    public static void Main()
    {
        // Specifying a file
        string path = @"file.txt";
  
        // Creating a string
        string createText = "GFG is a cs portal." + Environment.NewLine;
  
        // Overwriting the string to the file
        File.WriteAllText(path, createText);
  
        // Reading the contents of the file
        string readText = File.ReadAllText(path);
        Console.WriteLine(readText);
    }
}

输出:

GFG is a cs portal.

运行上述代码后,显示如上输出,文件file.txt内容如下所示:

file.txt




相关用法


注:本文由纯净天空筛选整理自Kanchan_Ray大神的英文原创作品 File.WriteAllText(String, String) Method in C# with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。