使用c编写从一个文本文件到其他文本文件的特定行#
我正在使用sharp develop。我正在使用C#制作一个Win App。我希望我的程序在驱动器c:中检查名为test的文本文件,并找到包含“=”的行,然后将此行写入驱动器c:中的其他新创建的文本文件。使用c编写从一个文本文件到其他文本文件的特定行#
你尝试过什么吗?
这里有两种方法来读取文件:
使用静态的文件类可用的方法。 ReadAllLines是特定的。如果你正在处理小文件,这已经足够了。接下来,一旦拥有数组,只需使用LINQ或任何其他迭代方法找到带有“=”的项目。一旦获得了该行,再次使用File类创建数据并将其写入该文件。
如果您正在处理大文件,请使用Stream。休息仍然相同。
using(StreamWriter sw = new StreamWriter(@"C:\destinationFile.txt"))
{
StreamReader sr = new StreamReader(@"C:\sourceFile.txt");
string line = String.Empty;
while ((line = sr.ReadLine()) != null)
{
if (line.Contains("=")) { sw.WriteLine(line)); }
}
sr.Close();
}
你还没有关闭'StreamReader'类的'file'对象,并且已经关闭了'sw'对象,因为它被'using'包装了,所以它不需要关闭。请更正这些。 – Aamir
是的,谢谢,我忘了关闭流。 –
尝试使用下面的衬板:
File.WriteAllLines(destinationFileName,
File.ReadAllLines(sourceFileName)
.Where(x => x.Contains("=")));
Boss,是'.Where(x => x.Contains(“=”)'是拉姆达表达式吗? –
@Daredev - 是的,它是。 – Enigmativity
下面是使用File.ReadLines
另一种简单的方法,LINQ的的Where
和File.AppendAllLines
var path1 = @"C:\test.txt";
var path2 = @"C:\test_out.txt";
var equalLines = File.ReadLines(path1)
.Where(l => l.Contains("="));
File.AppendAllLines(path2, equalLines.Take(1));
if (File.Exists(txtBaseAddress.Text))
{
StreamReader sr = new StreamReader(txtBaseAddress.Text);
string line;
string fileText = "";
while ((line = sr.ReadLine()) != null)
{
if (line.Contains("="))
{
fileText += line;
}
}
sr.Close();
if (fileText != "")
{
try
{
StreamWriter sw = new StreamWriter(txtDestAddress.Text);
sw.Write(fileText);
sw.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
位编辑Furqan的答案
using (StreamReader sr = new StreamReader(@"C:\Users\Username\Documents\a.txt"))
using (StreamWriter sw = new StreamWriter(@"C:\Users\Username\Documents\b.txt"))
{
int counter = 0;
string line = String.Empty;
while ((line = sr.ReadLine()) != null)
{
if (line.Contains("="))
{
sw.WriteLine(line);
if (++counter == 4)
{
sw.WriteLine();
counter = 0;
}
}
}
}
这不起作用 –
对不起,我现在检查它 –
now其正确的 –
您是否希望只输出带有“=”或所有这些行的第一行?如果源文件中没有“=”,你希望目标文件被重写,但是是空的还是单独留下? – Enigmativity