File Handling in C#

Mannan Ul Haq
0
In C#, the `File` class found within the `System.IO` namespace is your gateway to interact with files on your computer. The `System.IO` namespace provides various classes that help us to perform a variety of operations on files, like creating new files, reading or writing to existing ones, and more.

using System.IO;  // Include the System.IO namespace

File.FileMethod();  // Use methods from the File class

Let's have a look at some of the frequently used methods provided by the `File` class:

  • `AppendText()`: If you want to add some additional text to a file without overwriting its existing content, use this method.
  • `Copy()`: Need to duplicate a file? This method helps you copy an existing file to a new one.
  • `Create()`: Use this method when you want to create a new file. If the file already exists, it will be overwritten.
  • `Delete()`: Removes a file permanently.
  • `Exists()`: Checks if a particular file exists at the specified path.
  • `ReadAllText()`: Reads all the text from a file and returns it as a string.
  • `Replace()`: Allows you to replace one file's content with another file's content.
  • `WriteAllText()`: Writes a specified string to a file. It creates a new file if it doesn't exist, or overwrites an existing one.

Now let's walk through a basic example that illustrates writing to and reading from a file. We will use the `WriteAllText()` method to write some content to a file and then the `ReadAllText()` method to read the content:

using System.IO;  // Include the System.IO namespace

string message = "C# makes file handling easy!";  // Define a string message
File.WriteAllText("myfile.txt", message);  // Write the message to myfile.txt

string fileContent = File.ReadAllText("myfile.txt");  // Read the contents of myfile.txt
Console.WriteLine(fileContent);  // Display the content of myfile.txt

In this code, we first define a string called `message`. We then write this message to a file named "myfile.txt" using `File.WriteAllText()`. If "myfile.txt" doesn't exist, it's created automatically. If it does exist, the previous content is overwritten.

Next, we use `File.ReadAllText()` to read the contents of "myfile.txt" into the `fileContent` string. Finally, we output the content of `fileContent` to the console, which should be the message we initially wrote to the file.

Tags

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !