Notes

C# - File operations

author: Paul Kim

categories: csharp

tags: csharp

Performing File Operations in C# ⁠

  • StreamWriter - has methods to write to file synchronously (Write or WriteLine) or asynchronously (WriteAsync or WriteLineAsync).
  • File - used with .NET Framework applications has static methods to write text to a file (WriteAllLines and WriteAllText) or to append text to a file (AppendAllLines, AppendAllText or AppendText).
  • FileIO - used with Windows 8.x Store apps has asynchronous methods to write text to a file (WriteLinesAsync or WriteTextAsync) or to append text to a file (AppendLinesAsync or AppendTextAsync).

StreamWriter

/*
 * Write to a new file one line a a time.
 * If the file already exists, it will be overwritten.
 */
string pathString = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // MyDocuments folder
// string pathString = Directory.GetCurrentDirectory();  // Directory with .exe (usually bin/Debug or bin/Release
// string pathString = @"C:\temp"; // specific directory
const string fileName = @"WriteLines.txt";

using (var file = new StreamWriter(Path.Combine(pathString, fileName), append: false))
{
    string[] lines = { "a line", "b line", "c line" };
    foreach (string line in lines)
    {
        file.WriteLine(line);
    }

    for (int i = 0; i < 10; i++)
    {
        file.WriteLine("line" + i);
    }
}

/*
 * Append text to an exiting file one line a a time.
 * If the file does not exist, a new file will be created.
 * If the file exist, text will be appended to the file.
 * Note: passing 'true' as the second argument to StreamWriter constructor appends to file.
 */
string pathString = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
// string pathString = Directory.GetCurrentDirectory();  // Directory with .exe (usually bin/Debug or bin/Release
// string pathString = @"C:\temp"; // specific directory
const string fileName = @"WriteLines.txt";

using (var file = new StreamWriter(Path.Combine(pathString, fileName), append: true))
{
    string[] lines = { "a line", "b line", "c line" };
    foreach (string line in lines)
    {
        file.WriteLine(line);
    }

    for (int i = 0; i < 10; i++)
    {
        file.WriteLine("line" + i);
    }
}

StreamWriter methods

public static void Write<T>(string path, T t, bool append = false)
{
    using (var file = new StreamWriter(path, append))
    {
        file.Write(t.ToString());
    }
}

public static void WriteAll<T>(string path, IEnumerable<T> ts, bool append = false)
{
    using (var file = new StreamWriter(path, append))
    {
        foreach (var t in ts)
        {
            file.Write(t.ToString());
        }
    }
}

public static void WriteLine<T>(string path, T t, bool append = false)
{
    using (var file = new StreamWriter(path, append))
    {
        file.WriteLine(t.ToString());
    }
}

public static void WriteAllLines<T>(string path, IEnumerable<T> ts, bool append = false)
{
    using (var file = new StreamWriter(path, append))
    {
        foreach (var t in ts)
        {
            file.WriteLine(t.ToString());
        }
    }
}

StreamWriter Async methods

public static async void WriteAsync<T>(string path, T t, bool append = false)
{
    using (var file = new StreamWriter(path, append))
    {
        await file.WriteAsync(t.ToString());
    }
}

public static async void WriteAllAsync<T>(string path, IEnumerable<T> ts, bool append = false)
{
    using (var file = new StreamWriter(path, append))
    {
        foreach (var t in ts)
        {
            await file.WriteAsync(t.ToString());
        }
    }
}

public static async void WriteLineAsync<T>(string path, T t, bool append = false)
{
    using (var file = new StreamWriter(path, append))
    {
        await file.WriteLineAsync(t.ToString());
    }
}

public static async void WriteAllLinesAsync<T>(string path, IEnumerable<T> ts, bool append = false)
{
    using (var file = new StreamWriter(path, append))
    {
        foreach (var t in ts)
        {
            await file.WriteLineAsync(t.ToString());
        }
    }
}

File methods

string[] lines = { "First line", "Second line", "Third line" };
// WriteAllLines creates a file, writes a collection of strings to the file,
// and then closes the file.  You do NOT need to call Flush() or Close().
System.IO.File.WriteAllLines(@"c:\temp\MyTest.txt", lines);

string text = "A class is the most powerful data type in C#. Like a structure.\n";
// WriteAllText creates a file, writes the specified string to the file,
// and then closes the file.    You do NOT need to call Flush() or Close().
System.IO.File.WriteAllText(@"c:\temp\test.txt", text);

string[] lines = { "First line", "Second line", "Third line" };
// AppendAllLines creates a file if it does not exist, appends a collection of strings to the file,
// and then closes the file.  You do NOT need to call Flush() or Close().
System.IO.File.AppendAllLines(@"c:\temp\test.txt", lines);

string text = "A class is the most powerful data type in C#. Like a structure.\n";
// AppendAllText creates a file if it does not exist, appends the specified string to the file,
// and then closes the file.    You do NOT need to call Flush() or Close().
System.IO.File.AppendAllText(@"c:\temp\test.txt", text);

File methods (continued)

Console.WriteLine(File.Exists(@"c:\temp\test.txt") ? "File exists." : "File does not exist.");

// Open the file to read from.
using (StreamReader sr = File.OpenText(@"c:\temp\MyTest.txt"))
{
    string s = "";
    while ((s = sr.ReadLine()) != null)
    {
        Console.WriteLine(s);
    }
}

// Create a file to write to.
using (StreamWriter sw = File.CreateText(@"c:\temp\MyTest.txt"))
{
    sw.WriteLine("Hello");
    sw.WriteLine("And");
    sw.WriteLine("Welcome");
}

// This text is always added, making the file longer over time
// if it is not deleted.
using (StreamWriter sw = File.AppendText(@"c:\temp\MyTest.txt"))
{
    sw.WriteLine("This");
    sw.WriteLine("is Extra");
    sw.WriteLine("Text");
}

Source

ChromeEdgeFirefoxOpera

© 2021 paulkode.com. All rights reserved.