File.WriteAllLines 方法

定义

创建一个新文件,在其中写入一个或多个字符串,然后关闭该文件。

重载

WriteAllLines(String, IEnumerable<String>)

创建一个新文件,向其中写入一个字符串集合,然后关闭该文件。

WriteAllLines(String, String[])

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

WriteAllLines(String, IEnumerable<String>, Encoding)

使用指定的编码创建一个新文件,向其中写入一个字符串集合,然后关闭该文件。

WriteAllLines(String, String[], Encoding)

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

WriteAllLines(String, IEnumerable<String>)

Source:
File.cs
Source:
File.cs
Source:
File.cs

创建一个新文件,向其中写入一个字符串集合,然后关闭该文件。

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

要写入的文件。

contents
IEnumerable<String>

要写入到文件中的行。

例外

.NET Framework 和 .NET Core 版本早于 2.1: path 是一个零长度字符串,仅包含空格,或者包含方法GetInvalidPathChars()定义的一个或多个无效字符。

pathcontentsnull

path 无效(例如,它位于未映射的驱动器上)。

打开文件时发生 I/O 错误。

path 超出系统定义的最大长度。

path 的格式无效。

调用方没有所要求的权限。

path 指定了一个只读文件。

- 或 -

path 指定了一个隐藏文件。

- 或 -

当前平台不支持此操作。

- 或 -

path 是一个目录。

- 或 -

调用方没有所要求的权限。

示例

以下示例将示例数据文件中的选定行写入文件。

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

let dataPath = @"c:\temp\timestamps.txt"

let createSampleFile () =
    let timeStamp = DateTime(1700, 1, 1)

    use sw = new StreamWriter(dataPath)

    for i = 0 to 499 do
        let ts1 = timeStamp.AddYears i
        let ts2 = ts1.AddMonths i
        let ts3 = ts2.AddDays i
        ts3.ToLongDateString() |> sw.WriteLine

createSampleFile ()

let julyWeekends =
    File.ReadLines dataPath
    |> Seq.filter (fun line ->
        (line.StartsWith "Saturday"
         || line.StartsWith "Sunday")
        && line.Contains "July")

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

let marchMondays =
    File.ReadLines dataPath
    |> Seq.filter (fun line -> line.StartsWith "Monday" && line.Contains "March")

File.AppendAllLines(@"C:\temp\selectedDays.txt", marchMondays)
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) 。 如果需要在文件的开头包含 UTF-8 标识符(如字节顺序标记),请使用 WriteAllLines(String, IEnumerable<String>, Encoding) 编码方法 UTF8 重载。

如果目标文件已存在,则会将其截断并覆盖。

可以使用此方法为其构造函数(如 List<T>HashSet<T>SortedSet<T> 类)中采用 IEnumerable<T> 的集合类创建内容。

适用于

WriteAllLines(String, String[])

Source:
File.cs
Source:
File.cs
Source:
File.cs

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

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

要写入的文件。

contents
String[]

要写入文件的字符串数组。

例外

.NET Framework 和 .NET Core 版本早于 2.1: path 是零长度字符串,仅包含空格,或包含一个或多个无效字符。 你可以使用 GetInvalidPathChars() 方法查询无效字符。

pathcontentsnull

指定的路径和/或文件名超过了系统定义的最大长度。

指定的路径无效(例如,它位于未映射的驱动器上)。

打开文件时发生 I/O 错误。

path 指定了一个只读文件。

- 或 -

path 指定了一个隐藏文件。

- 或 -

当前平台不支持此操作。

- 或 -

path 指定了一个目录。

- 或 -

调用方没有所要求的权限。

path 的格式无效。

调用方没有所要求的权限。

示例

下面的代码示例演示如何使用 WriteAllLines 方法将文本写入文件。 在此示例中,如果文件尚不存在,则会创建一个文件,并将文本添加到该文件中。

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

let path = @"c:\temp\MyTest.txt"

// This text is added only once to the file.
if File.Exists path |> not then
    // Create a file to write to.
    let createText = [ "Hello"; "And"; "Welcome" ]
    File.WriteAllLines(path, createText)

// This text is always added, making the file longer over time
// if it is not deleted.
let appendText =
    "This is extra text" + Environment.NewLine

File.AppendAllText(path, appendText)

// Open the file to read from.
let readText = File.ReadAllLines path

for s in readText do
    printfn $"{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

注解

如果目标文件已存在,则会将其截断并覆盖。

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

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

适用于

WriteAllLines(String, IEnumerable<String>, Encoding)

Source:
File.cs
Source:
File.cs
Source:
File.cs

使用指定的编码创建一个新文件,向其中写入一个字符串集合,然后关闭该文件。

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

要写入的文件。

contents
IEnumerable<String>

要写入到文件中的行。

encoding
Encoding

要使用的字符编码。

例外

.NET Framework 和 .NET Core 版本早于 2.1: path 是一个零长度字符串,仅包含空格,或者包含方法GetInvalidPathChars()定义的一个或多个无效字符。

pathcontentsencodingnull

path 无效(例如,它位于未映射的驱动器上)。

打开文件时发生 I/O 错误。

path 超出系统定义的最大长度。

path 的格式无效。

调用方没有所要求的权限。

path 指定了一个只读文件。

- 或 -

path 指定了一个隐藏文件。

- 或 -

当前平台不支持此操作。

- 或 -

path 是一个目录。

- 或 -

调用方没有所要求的权限。

注解

如果目标文件已存在,则会将其截断并覆盖。

可以使用此方法创建包含以下项的文件:

适用于

WriteAllLines(String, String[], Encoding)

Source:
File.cs
Source:
File.cs
Source:
File.cs

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

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

要写入的文件。

contents
String[]

要写入文件的字符串数组。

encoding
Encoding

一个 Encoding 对象,它表示应用于字符串数组的字符编码。

例外

.NET Framework 和 .NET Core 版本早于 2.1: path 是零长度字符串,仅包含空格,或包含一个或多个无效字符。 你可以使用 GetInvalidPathChars() 方法查询无效字符。

pathcontentsnull

指定的路径和/或文件名超过了系统定义的最大长度。

指定的路径无效(例如,它位于未映射的驱动器上)。

打开文件时发生 I/O 错误。

path 指定了一个只读文件。

- 或 -

path 指定了一个隐藏文件。

- 或 -

当前平台不支持此操作。

- 或 -

path 指定了一个目录。

- 或 -

调用方没有所要求的权限。

path 的格式无效。

调用方没有所要求的权限。

示例

下面的代码示例演示如何使用 WriteAllLines 方法将文本写入文件。 在此示例中,如果文件尚不存在,则会创建一个文件,并将文本添加到该文件中。

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

let path = @"c:\temp\MyTest.txt"

// This text is added only once to the file.
if File.Exists path |> not then
    // Create a file to write to.
    let 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.
let appendText =
    "This is extra text" + Environment.NewLine

File.AppendAllText(path, appendText, Encoding.UTF8)

// Open the file to read from.
let readText = File.ReadAllLines(path, Encoding.UTF8)

for s in readText do
    printfn $"{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

注解

如果目标文件已存在,则会将其截断并覆盖。

给定字符串数组和文件路径,此方法将打开指定的文件,使用指定的编码将字符串数组写入文件,然后关闭该文件。

适用于