2011-02-21 5 views
1

을 사용하여 1) 다음과 같은 텍스트 파일이 있습니다.텍스트 파일에서 행을 읽고 필터링하는 방법 C#

Dilantha 
code 65 
po Bo 1255 
colombo 
sri lanka 

joy 
code 78 
toronto 
Canada 

2)하지만 아래의 결과를 원한다. 처음에는 텍스트 파일을 읽을 수 내의 requirment가)

Dilantha colombo  sri lanka 

joy  toronto  Canada 

3 (필자는 코드 (65)코드 78 개 부분을 원하지 않는), 다음 나는를 필터링 할 위의 결과는 입니다.

다음은 나의 코드입니다. 난 당신이 새로운 라인을 발생하면
이의에 무엇이 인쇄 "코드 XX"를 건너 뛸 줄을 당신이
사용 정규식 읽어 선을 연결하기 위해 모두 StringBuilder를 사용 C#

String line; 
    String path = "c:/sample.txt"; 

    StreamReader sr = new StreamReader(path); 
    while ((line = sr.ReadLine()) != null) 
    { 
     //display the readed lines in the text box 
     disTextBox.AppendText(line+Environment.NewLine); 
    } 
+0

이 예입니다. 나는 텍스트 파일의 큰 라인. plese 내 문제를 해결하는 데 도움이됩니다. – Chamal

+2

숙제? 파일의 모든 레코드가 동일한 형식으로 보장됩니까? – arootbeer

+0

아니요 다를 수 있습니다. – Chamal

답변

2

에 대한 문자열 목록 FO를 반환하는 함수를 만드는 방법 인쇄를 완료 한 후 하나의 그룹, 그 다음에 값을 보유 할 클래스?

public static List<string> ReadGroup(TextReader tr) 
{ 
    string line = tr.ReadLine(); 
    List<string> lines = new List<string>(); 
    while (line != null && line.Length > 0) 
    { 
     lines.Add(line); 
    } 

    // change this to line == null if you have groups with no lines 
    if (lines.Count == 0) 
    { 
     return null; 
    } 

    return lines; 
} 

그럼 당신은 목록에 인덱스 라인에 액세스 할 수 있습니다

String line; 
String path = "c:/sample.txt"; 

using (StreamReader sr = new StreamReader(path)) 
{ 
    while ((List<string> lines = ReadGroup(sr)) != null) 
    { 
     // you might want to check for lines.Count >= 4 if you will 
     // have groups with fewer lines to provide a better error 

     //display the readed lines in the text box 
     disTextBox.AppendText(string.Format("{0}\t{1}\t{2}{3}", 
      lines[0], lines[2], lines[3], Environment.NewLine); 
    } 
    sr.Close(); 
} 

난 당신의 첫 번째는 "포 보 1255"에 별도의 라인을 가지고 있음을 알 수 있습니다. 의미있는 파일을 만드는 데 필요한 형식이 무엇인지 알아야합니다. 그룹의 마지막 두 줄이 도시와 국가 인 경우 줄 수를 사용해야합니다.

class LineGroup // name whatever the data contains 
{ 
    public string Name { get; set; } 
    public string Code { get; set; } 
    public string City { get; set; } 
    public string Country { get; set; } 

    public LineGroup(List<string> lines) 
    { 
     if (lines == null || lines.Count < 4) 
     { 
      throw new ApplicationException("LineGroup file format error: Each group must have at least 4 lines"); 
     } 

     Name = lines[0]; 
     Code = lines[1]; 
     City = lines[lines.Count - 2]; 
     Country = lines[lines.Count - 1]; 
    } 
} 

그리고 프로세스 :

while ((List<string> lines = ReadGroup(sr) != null) 
{ 
    LineGroup group = new LineGroup(lines); 

    //display the readed lines in the text box 
    disTextBox.AppendText(string.Format("{0}\t{1}\t{2}{3}", 
     group.Name, group.City, group.Country, Environment.NewLine); 
} 
2

을 사용하고 있습니다 모두 StringBuilder
을 당신이 당신의 StringBuilder에 남아 아무것도 경우, 파일 함께

static Regex codeRegex = new Regex("^code [\\d]+", RegexOptions.Compiled); 

    static void Main(string[] args) 
    { 
     String line; 
     String path = "c:/sample.txt"; 
     StringBuilder sb = new StringBuilder(); 

     StreamReader sr = new StreamReader(path); 
     while ((line = sr.ReadLine()) != null) 
     { 
      line = line.Trim(); 

      if (codeRegex.IsMatch(line)) 
       continue; 

      if (string.IsNullOrEmpty(line)) 
      { 
       System.Console.Write(sb.ToString().Trim() + Environment.NewLine); 
       sb.Clear(); 
      } 
      else 
      { 
       sb.Append(line); 
       sb.Append("\t"); 
      } 
     } 

     if (!string.IsNullOrEmpty(sb.ToString().Trim())) 
      System.Console.Write(sb.ToString().Trim() + Environment.NewLine); 
    } 
0

그것을 밖으로 시도 :

foreach (var line in File.ReadLines(myFilePath)) { 
    if (line.Equals("code 65") || line.Equals("code 78")) 
    continue; 

    // some logic to format lines into columns.... 
    // ....Append(string.Format("{0, -15}{1, -15}{2, -15}", lineValue1, lineValue2, lineValue3)); 
} 
클래스로

.NET 4.0 이후에만 작동합니다.

관련 문제