File.WriteAllLines 方法

定义

创建一个新文件,在其中写入一个或多个字符串,然后关闭该文件。Creates a new file, writes one or more strings to the file, and then closes the file.

重载

WriteAllLines(String, String[], Encoding)

创建一个新文件,使用指定编码在其中写入指定的字符串数组,然后关闭该文件。Creates a new file, writes the specified string array to the file by using the specified encoding, and then closes the file.

WriteAllLines(String, IEnumerable<String>, Encoding)

使用指定的编码创建一个新文件,向其中写入一个字符串集合,然后关闭该文件。Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file.

WriteAllLines(String, String[])

创建一个新文件,在其中写入指定的字节数组,然后关闭该文件。Creates a new file, write the specified string array to the file, and then closes the file.

WriteAllLines(String, IEnumerable<String>)

创建一个新文件,向其中写入一个字符串集合,然后关闭该文件。Creates a new file, writes a collection of strings to the file, and then closes the file.

WriteAllLines(String, String[], Encoding)

创建一个新文件,使用指定编码在其中写入指定的字符串数组,然后关闭该文件。Creates a new file, writes the specified string array to the file by using the specified encoding, and then closes the file.

public:
 static void WriteAllLines(System::String ^ path, cli::array <System::String ^> ^ contents, System::Text::Encoding ^ encoding);
public static void WriteAllLines (string path, string[] contents, System.Text.Encoding encoding);
static member WriteAllLines : string * string[] * System.Text.Encoding -> unit
Public Shared Sub WriteAllLines (path As String, contents As String(), encoding As Encoding)

参数

path
String

要写入的文件。The file to write to.

contents
String[]

要写入文件的字符串数组。The string array to write to the file.

encoding
Encoding

一个 Encoding 对象,它表示应用于字符串数组的字符编码。An Encoding object that represents the character encoding applied to the string array.

例外

path 是一个长度为零的字符串,仅包含空格,或包含一个或多个由 InvalidPathChars 定义的无效字符。path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.

pathcontentsnullEither path or contents is null.

指定的路径和/或文件名超过了系统定义的最大长度。The specified path, file name, or both exceed the system-defined maximum length.

指定的路径无效(例如,它位于未映射的驱动器上)。The specified path is invalid (for example, it is on an unmapped drive).

打开文件时发生 I/O 错误。An I/O error occurred while opening the file.

path 指定了一个只读文件。path specified a file that is read-only.

- 或 --or- path 指定了一个隐藏文件。path specified a file that is hidden.

- 或 --or- 当前平台不支持此操作。This operation is not supported on the current platform.

- 或 --or- path 指定了一个目录。path specified a directory.

- 或 --or- 调用方没有所要求的权限。The caller does not have the required permission.

path 的格式无效。path is in an invalid format.

调用方没有所要求的权限。The caller does not have the required permission.

示例

下面的代码示例演示如何使用 WriteAllLines 方法向文件写入文本。The following code example demonstrates the use of the WriteAllLines method to write text to a file. 在此示例中,将创建一个文件(如果它尚不存在)并向其添加文本。In this example a file is created, if it doesn't already exist, and text is added to it.

using System;
using System.IO;
using System.Text;

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, Encoding.UTF8);
        }

        // 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, Encoding.UTF8);

        // Open the file to read from.
        string[] readText = File.ReadAllLines(path, Encoding.UTF8);
        foreach (string s in readText)
        {
            Console.WriteLine(s);
        }
    }
}
Imports System.IO
Imports System.Text

Public Class Test
    Public Shared Sub Main()
        Dim path As String = "c:\temp\MyTest.txt"
        Dim sw As StreamWriter

        ' This text is added only once to the file.
        If File.Exists(path) = False Then

            ' Create a file to write to.
            Dim createText() As String = {"Hello", "And", "Welcome"}
            File.WriteAllLines(path, createText, Encoding.UTF8)
        End If

        ' This text is always added, making the file longer over time
        ' if it is not deleted.
        Dim appendText As String = "This is extra text" + Environment.NewLine
        File.AppendAllText(path, appendText, Encoding.UTF8)

        ' Open the file to read from.
        Dim readText() As String = File.ReadAllLines(path, Encoding.UTF8)
        Dim s As String
        For Each s In readText
            Console.WriteLine(s)
        Next
    End Sub
End Class

注解

如果目标文件已存在,则覆盖该文件。If the target file already exists, it is overwritten.

如果给定字符串数组和文件路径,此方法将打开指定的文件,使用指定的编码将字符串数组写入文件,然后关闭该文件。Given a string array and a file path, this method opens the specified file, writes the string array to the file using the specified encoding, and then closes the file.

适用于

WriteAllLines(String, IEnumerable<String>, Encoding)

使用指定的编码创建一个新文件,向其中写入一个字符串集合,然后关闭该文件。Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file.

public:
 static void WriteAllLines(System::String ^ path, System::Collections::Generic::IEnumerable<System::String ^> ^ contents, System::Text::Encoding ^ encoding);
public static void WriteAllLines (string path, System.Collections.Generic.IEnumerable<string> contents, System.Text.Encoding encoding);
static member WriteAllLines : string * seq<string> * System.Text.Encoding -> unit
Public Shared Sub WriteAllLines (path As String, contents As IEnumerable(Of String), encoding As Encoding)

参数

path
String

要写入的文件。The file to write to.

contents
IEnumerable<String>

要写入到文件中的行。The lines to write to the file.

encoding
Encoding

要使用的字符编码。The character encoding to use.

例外

path 是长度为零的字符串,仅包含空格,或包含 GetInvalidPathChars() 方法定义的一个或多个无效字符。path is a zero-length string, contains only white space, or contains one or more invalid characters defined by the GetInvalidPathChars() method.

pathcontentsencodingnullEither path, contents, or encoding is null.

path 无效(例如,它位于未映射的驱动器上)。path is invalid (for example, it is on an unmapped drive).

打开文件时发生 I/O 错误。An I/O error occurred while opening the file.

path 超出系统定义的最大长度。path exceeds the system-defined maximum length.

path 的格式无效。path is in an invalid format.

调用方没有所要求的权限。The caller does not have the required permission.

path 指定了一个只读文件。path specified a file that is read-only.

- 或 --or- path 指定了一个隐藏文件。path specified a file that is hidden.

- 或 --or- 当前平台不支持此操作。This operation is not supported on the current platform.

- 或 --or- path 是一个目录。path is a directory.

- 或 --or- 调用方没有所要求的权限。The caller does not have the required permission.

注解

如果目标文件已存在,则覆盖该文件。If the target file already exists, it is overwritten.

您可以使用此方法创建包含以下内容的文件:You can use this method to create a file that contains the following:

适用于

WriteAllLines(String, String[])

创建一个新文件,在其中写入指定的字节数组,然后关闭该文件。Creates a new file, write the specified string array to the file, and then closes the file.

public:
 static void WriteAllLines(System::String ^ path, cli::array <System::String ^> ^ contents);
public static void WriteAllLines (string path, string[] contents);
static member WriteAllLines : string * string[] -> unit
Public Shared Sub WriteAllLines (path As String, contents As String())

参数

path
String

要写入的文件。The file to write to.

contents
String[]

要写入文件的字符串数组。The string array to write to the file.

例外

path 是一个长度为零的字符串,仅包含空格,或包含一个或多个由 InvalidPathChars 定义的无效字符。path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.

pathcontentsnullEither path or contents is null.

指定的路径和/或文件名超过了系统定义的最大长度。The specified path, file name, or both exceed the system-defined maximum length.

指定的路径无效(例如,它位于未映射的驱动器上)。The specified path is invalid (for example, it is on an unmapped drive).

打开文件时发生 I/O 错误。An I/O error occurred while opening the file.

path 指定了一个只读文件。path specified a file that is read-only.

- 或 --or- path 指定了一个隐藏文件。path specified a file that is hidden.

- 或 --or- 当前平台不支持此操作。This operation is not supported on the current platform.

- 或 --or- path 指定了一个目录。path specified a directory.

- 或 --or- 调用方没有所要求的权限。The caller does not have the required permission.

path 的格式无效。path is in an invalid format.

调用方没有所要求的权限。The caller does not have the required permission.

示例

下面的代码示例演示如何使用 WriteAllLines 方法向文件写入文本。The following code example demonstrates the use of the WriteAllLines method to write text to a file. 在此示例中,将创建一个文件(如果它尚不存在)并向其添加文本。In this example a file is created, if it doesn't already exist, and text is added to it.

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);
        }
    }
}
Imports System.IO

Public Class Test
    Public Shared Sub Main()
        Dim path As String = "c:\temp\MyTest.txt"
        Dim sw As StreamWriter

        ' This text is added only once to the file.
        If File.Exists(path) = False Then

            ' Create a file to write to.
            Dim createText() As String = {"Hello", "And", "Welcome"}
            File.WriteAllLines(path, createText)
        End If

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

        ' Open the file to read from.
        Dim readText() As String = File.ReadAllLines(path)
        Dim s As String
        For Each s In readText
            Console.WriteLine(s)
        Next
    End Sub
End Class

注解

如果目标文件已存在,则覆盖该文件。If the target file already exists, it is overwritten.

此方法的默认行为 WriteAllLines 是使用 utf-8 编码而不使用字节顺序标记 (BOM) 来写出数据。The default behavior of the WriteAllLines method is to write out data using UTF-8 encoding without a byte order mark (BOM). 如果需要在文件的开头包含 UTF-8 标识符,如字节顺序标记,请将 WriteAllLines(String, String[], Encoding) 方法重载用于 UTF8 编码。If it is necessary to include a UTF-8 identifier, such as a byte order mark, at the beginning of a file, use the WriteAllLines(String, String[], Encoding) method overload with UTF8 encoding.

如果给定字符串数组和文件路径,此方法将打开指定的文件,将字符串数组写入文件,然后关闭该文件。Given a string array and a file path, this method opens the specified file, writes the string array to the file, and then closes the file.

适用于

WriteAllLines(String, IEnumerable<String>)

创建一个新文件,向其中写入一个字符串集合,然后关闭该文件。Creates a new file, writes a collection of strings to the file, and then closes the file.

public:
 static void WriteAllLines(System::String ^ path, System::Collections::Generic::IEnumerable<System::String ^> ^ contents);
public static void WriteAllLines (string path, System.Collections.Generic.IEnumerable<string> contents);
static member WriteAllLines : string * seq<string> -> unit
Public Shared Sub WriteAllLines (path As String, contents As IEnumerable(Of String))

参数

path
String

要写入的文件。The file to write to.

contents
IEnumerable<String>

要写入到文件中的行。The lines to write to the file.

例外

path 是长度为零的字符串,仅包含空格,或包含 GetInvalidPathChars() 方法定义的一个或多个无效字符。path is a zero-length string, contains only white space, or contains one or more invalid characters defined by the GetInvalidPathChars() method.

pathcontentsnullEither path or contents is null.

path 无效(例如,它位于未映射的驱动器上)。path is invalid (for example, it is on an unmapped drive).

打开文件时发生 I/O 错误。An I/O error occurred while opening the file.

path 超出系统定义的最大长度。path exceeds the system-defined maximum length.

path 的格式无效。path is in an invalid format.

调用方没有所要求的权限。The caller does not have the required permission.

path 指定了一个只读文件。path specified a file that is read-only.

- 或 --or- path 指定了一个隐藏文件。path specified a file that is hidden.

- 或 --or- 当前平台不支持此操作。This operation is not supported on the current platform.

- 或 --or- path 是一个目录。path is a directory.

- 或 --or- 调用方没有所要求的权限。The caller does not have the required permission.

示例

下面的示例将示例数据文件中的选定行写入文件。The following example writes selected lines from a sample data file to a file.

using System;
using System.IO;
using System.Linq;

class Program
{
    static string dataPath = @"c:\temp\timestamps.txt";

    static void Main(string[] args)
    {
        CreateSampleFile();

        var JulyWeekends = from line in File.ReadLines(dataPath)
                           where (line.StartsWith("Saturday") ||
                           line.StartsWith("Sunday")) &
                           line.Contains("July")
                           select line;

        File.WriteAllLines(@"C:\temp\selectedDays.txt", JulyWeekends);

        var MarchMondays = from line in File.ReadLines(dataPath)
                           where line.StartsWith("Monday") &&
                           line.Contains("March")
                           select line;

        File.AppendAllLines(@"C:\temp\selectedDays.txt", MarchMondays);
    }

    static void CreateSampleFile()
    {
        DateTime TimeStamp = new DateTime(1700, 1, 1);

        using (StreamWriter sw = new StreamWriter(dataPath))
        {
            for (int i = 0; i < 500; i++)
            {
                DateTime TS1 = TimeStamp.AddYears(i);
                DateTime TS2 = TS1.AddMonths(i);
                DateTime TS3 = TS2.AddDays(i);
                sw.WriteLine(TS3.ToLongDateString());
            }
        }
    }
}
Imports System.IO
Imports System.Linq

Class Program
    Shared dataPath As String = "c:\temp\timestamps.txt"

    Public Shared Sub Main(ByVal args As String())
        CreateSampleFile()

        Dim JulyWeekends = From line In File.ReadLines(dataPath) _
            Where (line.StartsWith("Saturday") OrElse _
            line.StartsWith("Sunday")) And line.Contains("July") _
            Select line

        File.WriteAllLines("C:\temp\selectedDays.txt", JulyWeekends)

        Dim MarchMondays = From line In File.ReadLines(dataPath) _
            Where line.StartsWith("Monday") AndAlso line.Contains("March") _
            Select line

        File.AppendAllLines("C:\temp\selectedDays.txt", MarchMondays)
    End Sub

    Private Shared Sub CreateSampleFile()
        Dim TimeStamp As New DateTime(1700, 1, 1)

        Using sw As New StreamWriter(dataPath)
            For i As Integer = 0 To 499
                Dim TS1 As DateTime = TimeStamp.AddYears(i)
                Dim TS2 As DateTime = TS1.AddMonths(i)
                Dim TS3 As DateTime = TS2.AddDays(i)

                sw.WriteLine(TS3.ToLongDateString())
            Next
        End Using
    End Sub
End Class

注解

此方法的默认行为 WriteAllLines(String, IEnumerable<String>) 是使用 utf-8 编码而不使用字节顺序标记 (BOM) 来写出数据。The default behavior of the WriteAllLines(String, IEnumerable<String>) method is to write out data by using UTF-8 encoding without a byte order mark (BOM). 如果需要在文件的开头包含 UTF-8 标识符,如字节顺序标记,请将 WriteAllLines(String, IEnumerable<String>, Encoding) 方法重载用于 UTF8 编码。If it is necessary to include a UTF-8 identifier, such as a byte order mark, at the beginning of a file, use the WriteAllLines(String, IEnumerable<String>, Encoding) method overload with UTF8 encoding.

如果目标文件已存在,则覆盖该文件。If the target file already exists, it is overwritten.

您可以使用此方法创建集合类的内容,该集合类 IEnumerable<T> 在其构造函数中采用 List<T> ,如、 HashSet<T>SortedSet<T> 类。You can use this method to create the contents for a collection class that takes an IEnumerable<T> in its constructor, such as a List<T>, HashSet<T>, or a SortedSet<T> class.

适用于