System.IO.File.WriteAllLines 方法 (String, String[])

方法描述

创建一个新文件,在其中写入指定的字符串数组,然后关闭该文件。

语法定义(C# System.IO.File.WriteAllLines 方法 (String, String[]) 的用法)

public static void WriteAllLines(
	string path,
	string[] contents
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
path System-String 要写入的文件。
contents System-String[] 要写入文件的字符串数组。
返回值 void

提示和注释

如果目标文件已存在,则覆盖该文件。

WriteAllLines 方法的默认行为是使用无字节顺序标记 (BOM) 的 UTF-8 编码写出数据。 如果需要在文件开头包括一个 UTF-8 标识符(例如字节顺序标记),请使用 UTF8 编码的 WriteAllLines(String, String[], Encoding) 方法重载。

已知字符串数组和文件路径,此方法打开指定的文件,将字符串数组写入文件,然后关闭文件。

System.IO.File.WriteAllLines 方法 (String, String[])例子

在此示例中,如果文件尚不存在,则创建一个文件,并向其中添加文本。

using System;
using System.IO;
class Test
{
    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";

        // This text is added only once to the file.
        if (!File.Exists(path))
        {
            // Create a file to write to.
            string[] createText = { "Hello", "And", "Welcome" };
            File.WriteAllLines(path, createText);
        }

        // This text is always added, making the file longer over time
        // if it is not deleted.
        string appendText = "This is extra text" + Environment.NewLine;
        File.AppendAllText(path, appendText);

        // Open the file to read from.
        string[] readText = File.ReadAllLines(path);
        foreach (string s in readText)
        {
            Console.WriteLine(s);
        }
    }
}

异常

异常 异常描述
ArgumentException path 是一个零长度字符串,仅包含空白或者包含一个或多个由 InvalidPathChars 定义的无效字符。
ArgumentNullException path 或 contents 为 null。
PathTooLongException 指定的路径、文件名或者两者都超出了系统定义的最大长度。 例如,在基于 Windows 的平台上,路径必须小于 248 个字符,文件名必须小于 260 个字符。
DirectoryNotFoundException 指定的路径无效(例如,它位于未映射的驱动器上)。
IOException 打开文件时发生了 I/O 错误。
UnauthorizedAccessException
  • path 指定了一个只读文件。
  • 在当前平台上不支持此操作。
  • path 指定了一个目录。
  • 调用方没有所要求的权限。
FileNotFoundException 未找到 path 中指定的文件。
NotSupportedException path 的格式无效。
SecurityException 调用方没有所要求的权限。

命名空间

namespace: System.IO

程序集: mscorlib(在 mscorlib.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。