c#读取TXT文本最后一行数据
时间: 2024-02-07 21:02:56 浏览: 82
可以使用以下代码来读取TXT文本的最后一行数据:
```csharp
string filePath = "your_file_path";
string lastLine = string.Empty;
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (StreamReader sr = new StreamReader(fs))
{
string line;
while ((line = sr.ReadLine()) != null)
{
lastLine = line;
}
}
}
Console.WriteLine("The last line of the file is: " + lastLine);
```
首先,定义文件路径 `filePath` 和一个字符串变量 `lastLine` 用于存储最后一行数据。
然后,使用 `FileStream` 和 `StreamReader` 类来打开并读取文件。通过循环逐行读取文件,将每一行数据存储在 `lastLine` 变量中,最终得到最后一行数据。
最后,使用 `Console.WriteLine` 方法来输出最后一行数据。
相关问题
C#读取文本文件使用streamreading,读取txt,一行一行读取,直到最后
您可以使用以下代码来一行一行地读取文本文件并将其存储在字符串变量中,直到读取到文件的末尾为止:
```csharp
using System.IO;
string path = "your_file_path.txt";
string line;
string content = "";
using (StreamReader reader = new StreamReader(path))
{
while ((line = reader.ReadLine()) != null)
{
content += line + "\n"; // 将每行内容添加到字符串变量中
}
}
```
在上面的代码中,我们首先定义了文件路径变量 `path`,然后使用 `StreamReader` 类来读取文本文件。 `using` 语句用于确保在使用完 `StreamReader` 对象后将其关闭,从而释放资源。在 `while` 循环中,我们使用 `ReadLine()` 方法逐行读取文件内容,并将每行内容添加到字符串变量 `content` 中。当读取到文件的末尾时,`ReadLine()` 方法会返回 `null`,此时循环结束,`content` 变量中存储的就是整个文件的内容。
c# 读取本地txt文本
你可以使用C#的File类来读取本地的txt文本。以下是一个简单的代码示例,演示如何读取一个txt文件中的内容并将其打印到控制台上:
```csharp
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string filePath = @"C:\example.txt";
if (File.Exists(filePath))
{
string[] lines = File.ReadAllLines(filePath);
foreach (string line in lines)
{
Console.WriteLine(line);
}
}
else
{
Console.WriteLine("File does not exist.");
}
}
}
```
在此示例中,我们首先检查文件是否存在,然后使用File.ReadAllLines方法读取文件的所有行,将它们存储在字符串数组中,然后使用foreach循环遍历数组并将每行打印到控制台上。请注意,filePath变量存储txt文件的完整路径。