我想读取文本文件到它的第一个空行,然后删除我刚读过的那些行。 [英] I want to read a text file up to the first empty line in it and then delete those lines I have just read.
问题描述
我想读取文本文件,直到其中的第一个空行,然后在文本框中显示它,然后想要删除直到我刚从文本文件中读取的空行的行数。 br />
请帮我解决我的问题。
这是我的代码。使用此代码,我只能一次读取单行文本,然后删除该单行。但我想同时阅读多行文本,直到文本文件中的空行,然后删除这些行。
我是什么尝试过:
I want to read a text file up to the first empty line in it, then show it in a textbox and then want to delete the number of lines up to the empty line that I have just read from the text file.
Please help me to solve my problem.
Here is my code. Using this code I am only able to read the single line of text at a time and then delete that single line. But I want to read the multiple lines of text at the same time up to the empty line in my text file and then delete those lines.
What I have tried:
string line = null;
try
{
StreamReader sr = new StreamReader(fileNameAndPath);
line = sr.ReadLine();
Clipboard.SetText(line);
textBox1.Text = line;
sr.Close();
if (line == null || line == "")
{
//To remove the empty line from the text file
var file = new List<string>(File.ReadAllLines(fileNameAndPath));
file.RemoveAt(0);
File.WriteAllLines(fileNameAndPath, file.ToArray());
}
}
catch
{
MessageBox.Show("Text file is empty");
}
推荐答案
使用这段代码我只能一次读取单行文本,然后删除那一行。
Using this code I am only able to read the single line of text at a time and then delete that single line.
这很好,因为这正是这段代码的假设要做。
您的代码需要完全重写。
首先,阅读所有文件行到列表:
And it is well because this is exactly what this code is supposed to do.
Your code need a complete rewrite.
First, read all lines of file to a list:
var file = new List<string>(File.ReadAllLines(fileNameAndPath));
然后扫描每一行,直到找到一个空行。
一旦你知道了这个位置,删除你想要的东西删除。
then scan each line until you find an empty one.
once you know the position, delete what you want to remove.
这篇关于我想读取文本文件到它的第一个空行,然后删除我刚读过的那些行。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!