Program to Read the First Line From a File - (C# Basic Programs)
Reading a file is a common operation in programming. In this tutorial, we will discuss a C# program to read the first line from a file.
Syntax
The syntax for reading the first line from a file in C# is as follows:
using System.IO;
string fileName = "file.txt";
string firstLine = File.ReadLines(fileName).First();
Example
Suppose we have a file called data.txt
that contains the following text:
This is the first line
This is the second line
This is the third line
To read the first line from this file in C#, we can write the following program:
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string fileName = "data.txt";
string firstLine = File.ReadLines(fileName).First();
Console.WriteLine("The first line of the file is:");
Console.WriteLine(firstLine);
}
}
Output
When we run this program, the output will be:
The first line of the file is:
This is the first line
Explanation
In this program, we use the File
object from the System.IO
namespace to read the lines from the file. We then use the First()
method to get the first line from the file. Finally, we print out the first line to the console.
Use
Reading the first line from a file is a common operation in programming. This technique can be used in a variety of scenarios, such as:
- Reading configuration settings from a file
- Parsing data from a CSV file
- Checking the format of a data file before processing it
Summary
In this tutorial, we discussed a program to read the first line from a file using C# programming language. We covered the syntax, example, output, explanation, use, and summary of reading the first line from a file. This technique is a useful tool for reading and processing data from a file in many programming scenarios.