C# Language File and Stream I/O

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Introduction

Manages files.

Syntax

  • new System.IO.StreamWriter(string path)
  • new System.IO.StreamWriter(string path, bool append)
  • System.IO.StreamWriter.WriteLine(string text)
  • System.IO.StreamWriter.WriteAsync(string text)
  • System.IO.Stream.Close()
  • System.IO.File.ReadAllText(string path)
  • System.IO.File.ReadAllLines(string path)
  • System.IO.File.ReadLines(string path)
  • System.IO.File.WriteAllText(string path, string text)
  • System.IO.File.WriteAllLines(string path, IEnumerable<string> contents)
  • System.IO.File.Copy(string source, string dest)
  • System.IO.File.Create(string path)
  • System.IO.File.Delete(string path)
  • System.IO.File.Move(string source, string dest)
  • System.IO.Directory.GetFiles(string path)

Parameters

ParameterDetails
pathThe location of the file.
appendIf the file exist, true will add data to the end of the file (append), false will overwrite the file.
textText to be written or stored.
contentsA collection of strings to be written.
sourceThe location of the file you want to use.
destThe location you want a file to go to.

Remarks

  • Always make sure to close Stream objects. This can be done with a using block as shown above or by manually calling myStream.Close().
  • Make sure the current user has necessary permissions on the path you are trying to create the file.
  • Verbatim strings should be used when declaring a path string that includes backslashes, like so: @"C:\MyFolder\MyFile.txt"


Got any C# Language Question?