2012-09-28 39 views
0

我正在使用sharp develop。我正在使用C#制作一个Win App。我希望我的程序在驱动器c:中检查名为test的文本文件,并找到包含“=”的行,然后将此行写入驱动器c:中的其他新创建的文本文件。使用c编写从一个文本文件到其他文本文件的特定行#

+1

您是否希望只输出带有“=”或所有这些行的第一行?如果源文件中没有“=”,你希望目标文件被重写,但是是空的还是单独留下? – Enigmativity

回答

0

你尝试过什么吗?

这里有两种方法来读取文件:

  1. 使用静态的文件类可用的方法。 ReadAllLines是特定的。如果你正在处理小文件,这已经足够了。接下来,一旦拥有数组,只需使用LINQ或任何其他迭代方法找到带有“=”的项目。一旦获得了该行,再次使用File类创建数据并将其写入该文件。

  2. 如果您正在处理大文件,请使用Stream。休息仍然相同。

1
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(); 
} 
+1

你还没有关闭'StreamReader'类的'file'对象,并且已经关闭了'sw'对象,因为它被'using'包装了,所以它不需要关闭。请更正这些。 – Aamir

+0

是的,谢谢,我忘了关闭流。 –

2

尝试使用下面的衬板:

File.WriteAllLines(destinationFileName, 
    File.ReadAllLines(sourceFileName) 
     .Where(x => x.Contains("="))); 
+0

Boss,是'.Where(x => x.Contains(“=”)'是拉姆达表达式吗? –

+0

@Daredev - 是的,它是。 – Enigmativity

2

下面是使用File.ReadLines另一种简单的方法,LINQ的的WhereFile.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)); 
0
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); 
     } 
    } 
} 
0

位编辑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; 
      } 
     } 
    } 
} 
+0

这不起作用 –

+0

对不起,我现在检查它 –

+0

now其正确的 –

相关问题