How to read specific data from a file in C#?
In C#, you can use the StreamReader class to read data from a file. Here is an example code demonstrating how to read some data from a file.
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "path_to_your_file"; // 替换为实际文件路径
try
{
using (StreamReader sr = new StreamReader(filePath))
{
// 读取文件中的前10行数据
int lineCount = 0;
string line;
while ((line = sr.ReadLine()) != null && lineCount < 10)
{
Console.WriteLine(line);
lineCount++;
}
}
}
catch (Exception e)
{
Console.WriteLine("文件读取错误: " + e.Message);
}
}
}
The code above will read the first 10 lines of data from the file and print each line to the console. Feel free to modify the code as needed to read other parts of the file.