C# 从现有文件创建新文件
我有一个文本文件,当我使用streamreader打开它时,它看起来是这样的:(这个“删除”只是为了告诉你我想做什么) A、 1,2,3,4,5 B、 1,2,2,2,2 B、 1,1,1,1,1,1 A、 2,2,3,4,5--拆下 A、 1,2,3,4,5 A、 2,2,3,4,5--拆下 B、 1,2,2,2,2-取下 B、 1,1,1,1,1-取下 A、 1,2,3,4,5 B、 1,2,2,2,2 “A”是父行,“B”是父行正下方的子行。有些A可能没有子行。基本上,我想要一个新的文本文件,它只包含a及其子项(B),其中a行中的第二个字段不包含2。因此,我的新文本文件(使用streamwriter)如下所示: A, 1, 2, 3, 4, 5 B, 1, 2, 2, 2, 2 B, 1, 1, 1, 1, 1 A, 1, 2, 3, 4, 5 A, 1, 2, 3, 4, 5 B, 1, 2, 2, 2, 2 A、 1,2,3,4,5 B、 1,2,2,2,2 B、 1,1,1,1,1,1 A、 1,2,3,4,5 A、 1,2,3,4,5 B、 1,2,2,2,2 我可以得到A行,没有“2”。。。但是很难让孩子们在下面画线 有人帮忙吗 我想我已经成功了,但并不优雅:C# 从现有文件创建新文件,c#,C#,我有一个文本文件,当我使用streamreader打开它时,它看起来是这样的:(这个“删除”只是为了告诉你我想做什么) A、 1,2,3,4,5 B、 1,2,2,2,2 B、 1,1,1,1,1,1 A、 2,2,3,4,5--拆下 A、 1,2,3,4,5 A、 2,2,3,4,5--拆下 B、 1,2,2,2,2-取下 B、 1,1,1,1,1-取下 A、 1,2,3,4,5 B、 1,2,2,2,2 “A”是父行,“B”是父行正下方的子行。有些A可能没有子行。基本上,我想要一个新的文本文
List<string> str = new List<string>();
while (!file.EndOfStream)
{
var line = file.ReadLine();
str.Add(line);
}
file.Close();
using (var sw = new StreamWriter(file))
{
for(int i = 0; i <= str.Count-1; i++)
{
var values = str[i].Split(',');
if (values[0] == "A" && values[1] != "2")
{
sw.WriteLine(str[i]);
int j = i+1;
for (int e = j; e <= str.Count - 1; e++)
{
var values2 = str[e].Split(',');
if (values2[0] == "B")
{
sw.WriteLine(str[e]);
}else if(values2[0] == "A")
{
break;
}
}
}
}
}
List str=newlist();
而(!file.EndOfStream)
{
var line=file.ReadLine();
str.Add(行);
}
file.Close();
使用(var sw=新StreamWriter(文件))
{
对于(int i=0;i我可能会这样做。请注意,这假设文件始终与您的示例类似,并且不会进行错误检查:
using (StreamReader reader = new StreamReader(inputFile))
using (StreamWriter writer = new StreamWriter(outputFile))
{
bool delete = false;
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
string[] lineItems = line.Split(',');
if (lineItems[0].Trim() == "A")
delete = lineItems[1].Trim() == "2";
if (!delete)
writer.WriteLine(line);
}
}
由于您已经从当前的A
中知道您将删除它以及它后面的任何B,因此您可以简单地将状态保留为布尔值
static void ProcessStream(TextReader input, TextWriter output)
{
bool remove = false;
string line;
while ((line = input.ReadLine()) != null)
{
var parts = line.Split(',');
//for A, decide to remove this and next lines
if (parts[0] == "A")
remove = parts[1].Contains("2");
if (!remove)
output.WriteLine(line);
}
}
你能给我们看一下你到目前为止的代码吗?你的删除标准一点也不清楚。我添加了到目前为止的代码。这似乎很有效。我必须继续测试,但它并不优雅。问题是什么?删除标准,还是实际编写文件?你说的“有效”是什么意思?基本上,我“认为”我让它工作了——也就是说,我能够在它和孩子们(B)之后立即得到“A”行和“2”行,但我不认为这很优雅,我想知道是否有人有更好的方法?谢谢!!,这肯定比我的优雅多了!
static void ProcessStream(TextReader input, TextWriter output)
{
bool remove = false;
string line;
while ((line = input.ReadLine()) != null)
{
var parts = line.Split(',');
//for A, decide to remove this and next lines
if (parts[0] == "A")
remove = parts[1].Contains("2");
if (!remove)
output.WriteLine(line);
}
}