Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • C# - Get Started
  • C# - Version History
  • C# - First Program
  • C# - Keywords
  • C# - Class and Objects
  • C# - Namespace
  • C# - Variables
  • C# - Implicitly-Typed Variables
  • C# - Data Types
  • Numbers
  • Strings
  • DateTime
  • Structure
  • Enum
  • StringBuilder
  • Anonymous Types
  • Dynamic Types
  • Nullable Types
  • C# - Value & Reference Types
  • C# - Interface
  • C# - Operators
  • C# - if else Statements
  • C# - Ternary Operator ?:
  • C# - Switch
  • C# - For Loop
  • C# - While Loop
  • C# - Do-while Loop
  • C# - Partial Class
  • C# - Static
  • C# - Array
  • Multidimensional Array
  • Jagged Array
  • C# - Indexer
  • C# - Generics
  • Generic Constraints
  • C# - Collections
  • ArrayList
  • List
  • SortedList
  • Dictionary
  • Hashtable
  • Stack
  • Queue
  • C# - Tuple
  • C# - ValueTuple
  • C# - Built-in Exceptions
  • Exception Handling
  • throw
  • Custom Exception
  • C# - Delegates
  • Func Delegate
  • Action Delegate
  • Predicate Delegate
  • Anonymous Methods
  • C# - Events
  • C# - Covariance
  • C# - Extension Method
  • C# - Stream I/O
  • C# - File
  • C# - FileInfo
  • C# - Object Initializer
  • OOP - Overview
  • Object-Oriented Programming
  • Abstraction
  • Encapsulation
  • Association & Composition
  • Inheritance
  • Polymorphism
  • Method Overriding
  • Method Hiding
  • C# - Solid Principles
  • Single Responsibility Principle
  • Open/Closed Principle
  • Liskov Substitution Principle
  • Interface Segregation Principle
  • Dependency Inversion Principle
  • Design Patterns
  • Singleton
  • Abstract Factory
  • Factory Method
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

Working with Files & Directories in C#

C# provides the following classes to work with the File system. They can be used to access directories, access files, open files for reading or writing, create a new file or move existing files from one location to another, etc.

Class NameUsage
FileFile is a static class that provides different functionalities like copy, create, move, delete, open for reading or /writing, encrypt or decrypt, check if a file exists, append lines or text to a file's content, get last access time, etc.
FileInfoThe FileInfo class provides the same functionality as a static File class. You have more control on how you do read/write operations on a file by writing code manually for reading or writing bytes from a file.
DirectoryDirectory is a static class that provides functionality for creating, moving, deleting and accessing subdirectories.
DirectoryInfoDirectoryInfo provides instance methods for creating, moving, deleting and accessing subdirectories.
PathPath is a static class that provides functionality such as retrieving the extension of a file, changing the extension of a file, retrieving the absolute physical path, and other path related functionalities.

File

C# includes static File class to perform I/O operation on physical file system. The static File class includes various utility method to interact with physical file of any type e.g. binary, text etc.

Use this static File class to perform some quick operation on physical file. It is not recommended to use File class for multiple operations on multiple files at the same time due to performance reasons. Use FileInfo class in that scenario.

Important Methods of Static File Class

MethodUsage
AppendAllLinesAppends lines to a file, and then closes the file. If the specified file does not exist, this method creates a file, writes the specified lines to the file, and then closes the file.
AppendAllTextOpens a file, appends the specified string to the file, and then closes the file. If the file does not exist, this method creates a file, writes the specified string to the file, then closes the file.
AppendTextCreates a StreamWriter that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist.
CopyCopies an existing file to a new file. Overwriting a file of the same name is not allowed.
CreateCreates or overwrites a file in the specified path.
CreateTextCreates or opens a file for writing UTF-8 encoded text.
DecryptDecrypts a file that was encrypted by the current account using the Encrypt method.
DeleteDeletes the specified file.
EncryptEncrypts a file so that only the account used to encrypt the file can decrypt it.
ExistsDetermines whether the specified file exists.
GetAccessControlGets a FileSecurity object that encapsulates the access control list (ACL) entries for a specified file.
MoveMoves a specified file to a new location, providing the option to specify a new file name.
OpenOpens a FileStream on the specified path with read/write access.
ReadAllBytesOpens a binary file, reads the contents of the file into a byte array, and then closes the file.
ReadAllLinesOpens a text file, reads all lines of the file, and then closes the file.
ReadAllTextOpens a text file, reads all lines of the file, and then closes the file.
ReplaceReplaces the contents of a specified file with the contents of another file, deleting the original file, and creating a backup of the replaced file.
WriteAllBytesCreates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.
WriteAllLinesCreates a new file, writes a collection of strings to the file, and then closes the file.
WriteAllTextCreates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.

Append Text Lines

Use AppendAllLines() method to append multiple text lines to the specified file as shown below.

Example: Append all text lines to a file
string dummyLines = "This is first line." + Environment.NewLine +
                    "This is second line." + Environment.NewLine +
                    "This is third line.";

//Opens DummyFile.txt and append lines. If file is not exists then create and open.
File.AppendAllLines(@"C:DummyFile.txt", dummyLines.Split(Environment.NewLine.ToCharArray()).ToList<string>());

Append String

Use File.AppendAllText() method to append string to a file in single line of code as shown below.

Example: Append string to a file
//Opens DummyFile.txt and append Text. If file is not exists then create and open.
File.AppendAllText(@"C: DummyFile.txt", "This is File testing");
</code></pre>
            <div className="card-footer example-footer"></div>     </div>
    </div>
    <h2>Overwrite Text</h2>
    <p>Use <i>File.WriteAllText()</i> method to write texts to the file. Please note that it will not append text but overwrite existing texts.</p>
    <div className="card code-panel">
        <div className="card-header example-title">Example: Overwrite existing texts</div>
        <div className="panel-body">
            <pre className="csharpcode">
<code>//Opens DummyFile.txt and write texts. If file is not exists then create and open.
File.WriteAllText(@"C:DummyFile.txt", "This is dummy text");

The following example shows how to perform different operations using static File class.

Example: Multiple File operations
//Check whether file is exists or not at particular location
bool isFileExists = File.Exists(@"C: DummyFile.txt"); // returns false

//Copy DummyFile.txt as new file DummyFileNew.txt
File.Copy(@"C:DummyFile.txt", @"D:NewDummyFile.txt");

//Get when the file was accessed last time 
DateTime lastAccessTime = File.GetLastAccessTime(@"C:DummyFile.txt");

//get when the file was written last time
DateTime lastWriteTime = File.GetLastWriteTime(@"C:DummyFile.txt");

// Move file to new location
File.Move(@"C:DummyFile.txt", @"D:DummyFile.txt");

//Open file and returns FileStream for reading bytes from the file
FileStream fs = File.Open(@"D:DummyFile.txt", FileMode.OpenOrCreate);

//Open file and return StreamReader for reading string from the file
StreamReader sr = File.OpenText(@"D:DummyFile.txt");
    
//Delete file
File.Delete(@"C:DummyFile.txt");

Thus, it is easy to work with physical file using static File class. However, if you want more flexibility then use FileInfo class. The same way, use static Directory class to work with physical directories.

Visit MSDN to know all the methods of the static File class.

TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.