File.WriteAllLines File.WriteAllLines File.WriteAllLines File.WriteAllLines Method

Definition

Creates a new file, writes one or more strings to the file, and then closes the file.

Overloads

WriteAllLines(String, String[], Encoding) WriteAllLines(String, String[], Encoding) 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) WriteAllLines(String, IEnumerable<String>, Encoding) 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[]) WriteAllLines(String, String[]) WriteAllLines(String, String[]) WriteAllLines(String, String[])

Creates a new file, write the specified string array to the file, and then closes the file.

WriteAllLines(String, IEnumerable<String>) WriteAllLines(String, IEnumerable<String>) WriteAllLines(String, IEnumerable<String>) 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) WriteAllLines(String, String[], Encoding) 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
Parameters
path
String String String String

The file to write to.

contents
String[]

The string array to write to the file.

encoding
Encoding Encoding Encoding Encoding

An Encoding object that represents the character encoding applied to the string array.

Exceptions

path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.

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).

An I/O error occurred while opening the file.

path specified a file that is read-only.

-or-

This operation is not supported on the current platform.

-or-

path specified a directory.

-or-

The caller does not have the required permission.

The caller does not have the required permission.

Examples

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
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

Remarks

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.

Security

FileIOPermission
for access to write to a file or directory. Associated enumeration: Write

WriteAllLines(String, IEnumerable<String>, Encoding) WriteAllLines(String, IEnumerable<String>, Encoding) 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
Parameters
path
String String String String

The file to write to.

contents
IEnumerable<String>

The lines to write to the file.

encoding
Encoding Encoding Encoding Encoding

The character encoding to use.

Exceptions

path is a zero-length string, contains only white space, or contains one or more invalid characters defined by the GetInvalidPathChars() method.

An I/O error occurred while opening the file.

The caller does not have the required permission.

path specifies a file that is read-only.

-or-

This operation is not supported on the current platform.

-or-

path is a directory.

-or-

The caller does not have the required permission.

Remarks

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[]) WriteAllLines(String, String[]) WriteAllLines(String, String[]) 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())
Parameters
path
String String String String

The file to write to.

contents
String[]

The string array to write to the file.

Exceptions

path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.

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).

An I/O error occurred while opening the file.

path specified a file that is read-only.

-or-

This operation is not supported on the current platform.

-or-

path specified a directory.

-or-

The caller does not have the required permission.

The caller does not have the required permission.

Examples

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
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

Remarks

If the target file already exists, it is overwritten.

The default behavior of the WriteAllLines method is to write out data using UTF-8 encoding without a byte order mark (BOM). 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.

Security

FileIOPermission
for access to write to a file or directory. Associated enumeration: Write

WriteAllLines(String, IEnumerable<String>) WriteAllLines(String, IEnumerable<String>) WriteAllLines(String, IEnumerable<String>) 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))
Parameters
path
String String String String

The file to write to.

contents
IEnumerable<String>

The lines to write to the file.

Exceptions

path is a zero-length string, contains only white space, or contains one or more invalid characters defined by the GetInvalidPathChars() method.

An I/O error occurred while opening the file.

The caller does not have the required permission.

path specifies a file that is read-only.

-or-

This operation is not supported on the current platform.

-or-

path is a directory.

-or-

The caller does not have the required permission.

Examples

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
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

Remarks

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). 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.

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.

Applies to