2014-03-18 9 views
0

일부 데이터를 기반으로 텍스트 줄을 파일의 기존 줄로 바꾸고 싶습니다. 일부 코드 블록을 개발했지만 작동하지 않았습니다. 내 텍스트 파일은 다음과 같이이다 : -C#에서 동일한 텍스트 파일의 다른 줄로 한 줄 바꾸기

g_start-fd,g_start-cnst,g_start-eq,mv-mv_size,mv-mv_alloy,mv-mv_argmt,mv-mv_ps,xfrmr-kva,g_end-line_t,g_end-str_num,g_end-cmt,g_end-str_coord-Latitude,g_end-str_coord-Longitude 
28F1Y,oh,mv oh,120,al,oh_3,P45R24,,i,P45R25,,9.53725695,-0.86668464 
28F1Y,oh,mv oh,120,al,oh_3,P45R25,,i,P45R42,,9.5468355,-0.85948875 
28F1Y,oh,mv oh,120,al,oh_3,P45R42,,i,P45R49,,9.55073989,-0.85625858 
28F1Y,oh,mv oh,120,al,oh_3,P45R49,,a,P45R25,,, 
28F1Y,oh,mv oh,120,al,oh_3,P45R54,,i,P45R55,,9.5544981,-0.85359626 
28F1Y,oh,mv xfrmr,120,al,oh_3,P45R55,5000,e,P45R56,Substation,9.5549907,-0.85303108 
28F1Y,ug,mv,185,al,xlpe_3,P45R56,,e,P45R55,,, 
28F1Y,ug,mv,185,al,xlpe_3,P45R57,,s,P45R58,Take off from ring main,9.55387622,-0.8538622 
28F1Y,oh,mv oh,120,al,oh_3,P45R58,,a,P45R73,,9.54513187,-0.86060037 
28F1Y,oh,mv oh,120,al,oh_3,P45R73,,a,P45R77,,9.5417936,-0.86098952 
28F1Y,oh,mv oh,120,al,oh_3,P45R77,,a,P45R80,,9.54144045,-0.85857346 
28F1Y,oh,mv oh,120,al,oh_3,P45R80,,a,P45R86,,9.53675765,-0.85935176 
28F1Y,oh,mv,120,al,oh_3,P45R86,,e,P45R80,,, 

내 응용 프로그램 정지 작업이 코드 실행하면 코드 작업을 강제로

string fileName1 = "D:\\WriteTextWork\\Line1.txt"; ; 

OpenFileDialog pfdg = new OpenFileDialog(); 
if (pfdg.ShowDialog() == DialogResult.OK) 
{ 
    fileName1 = pfdg.FileName; 
} 

if (File.Exists(fileName1)) 
{ 
    StreamReader SR = new StreamReader(fileName1); 

    string Data = null; 
    int count = 0; 

    while ((Data = SR.ReadLine()) != null) 
    { 
     count++; 
     if (count > 1) 
     { 
      string CopyText = ""; 
      String[] SplitData = Data.Split(','); 
      if (SplitData[9] != null && SplitData[11] != null) 
      { 
       CopyText = Data; 
       string data1 = SR.ReadLine(); 
       //MessageBox.Show(CopyText); 
      } 
      using (StreamReader SR1 = new StreamReader(fileName1)) 
      { 
       //var SW = new StreamWriter(resultString1); 
       string line; 
       while ((line = SR1.ReadLine()) != null) 
       { 


        //String TrimData2 = line.Trim(); 
        String[] SplitText = line.Split(','); 
        if (SplitText[9] == SplitData[9] && SplitText[11] == null) 
        { 
         using (StreamWriter SW = new StreamWriter(resultString1)) 
         { 
          SW.WriteLine(CopyText); 
          MessageBox.Show(CopyText); 
          SW.Close(); 
         } 

        } 
       } 
       SR1.Close(); 
      } 
     } 
    } 
} 
+0

오류를 게시 할 수 있으며 코드의 어느 부분에서 오류가 발생합니까? – failedprogramming

+3

"작동 중지"는 어떤 일이 일어날 지 기술적 설명이 아닙니다. 도움이 필요하면 프로그래머처럼 생각하고 기술적 인 관찰을 한 다음 궁금한 사항을보고해야합니다. –

+2

중첩 된 판독기와 작성기를 작성하고 있습니다. 그것에 대해 생각해보십시오. 이해가 되니? 당신의 논리와 일치하는 동일한 레벨과 사본 줄에 1 명의 독자와 1 명의 작가를 고려하십시오. –

답변

0

메서드를 계속 진행하기 위해 이벤트 (btn_proceed_Click)를 만들었으므로 원하는 곳에 배치 할 수 있습니다. 전체 코드는 다음과 같습니다.

private void btn_proceed_Click(object sender, EventArgs e) 
    { 
     // This dictionary contains indices of rows we need to replace. 
     Dictionary<int, int> replaceable = new Dictionary<int, int>(); 
     replaceable.Add(4, 1); 
     replaceable.Add(7, 5); 
     replaceable.Add(13, 11); 

     string input = String.Empty; 
     OpenFileDialog pfdg = new OpenFileDialog(); 
     if (pfdg.ShowDialog() == DialogResult.OK) 
     { 
      input = pfdg.FileName; 
     } 
     // I placed the result into the another file called result.txt. You can use output path as same as input to overwrite the file. 
     ReplaceLines(replaceable, input, @"C:\Users\Wallstrider\Documents\Visual Studio 2010\Projects\result.txt", 9); 
    } 
    /// <summary> 
    /// Replaces lines of the file depends on 9th item is exist. 
    /// </summary> 
    /// <param name="replaceable">Rows incides to replace.</param> 
    /// <param name="input_path">Path to the input file.</param> 
    /// <param name="output_path">Path to the output file.</param> 
    /// <param name="has_value_index">Index of a split data value in the row.</param> 
    private void ReplaceLines(Dictionary<int, int> replaceable, string input_path, string output_path, int has_value_index) 
    { 
     if (File.Exists(input_path)) 
     { 
      string file; 
      file = new StreamReader(input_path).ReadToEnd(); 

      string[] lines = file.Split(new char[] { '\n' }); 
      List<string[]> split_data = new List<string[]>(); 

      for (int i = 0; i < lines.Length; i++) 
       split_data.Add(lines[i].Split(',')); 

      List<int> allowed_for_replace_indices = new List<int>(); 
      List<int> not_allowed_for_replace_indices = new List<int>(); 

      // Check if the row has the value of 9th item then we are allowed to replace rows. 
      for (int i = 1; i < split_data.Count; i++) 
      { 
       if (split_data[i][has_value_index] != String.Empty) 
        allowed_for_replace_indices.Add(i); 
       else 
        not_allowed_for_replace_indices.Add(i); 
      } 
      List<int> rows_replaced = new List<int>(); 
      List<int> rows_not_replaced = new List<int>(); 
      // Loop through our replaceable indices dictionary. 
      for (int i = 0; i < replaceable.Count; i++) 
      { 
       int key = replaceable.ElementAt(i).Key; 
       int value = replaceable.ElementAt(i).Value; 
       // if both rows have 9th item then we can start replacement. 
       if (allowed_for_replace_indices.Contains(key) && allowed_for_replace_indices.Contains(value)) 
       { 
        string temp = lines[value]; 
        lines[value] = lines[key]; 
        lines[key] = temp; 
        rows_replaced.Add(key); 
        rows_replaced.Add(value); 
       } 
       else 
       { 
        rows_not_replaced.Add(key); 
        rows_not_replaced.Add(value); 
       } 
      } 

      using (StreamWriter sw = new StreamWriter(output_path)) 
      { 
       for (int i = 0; i < lines.Length; i++) 
        sw.WriteLine(lines[i]); 
       sw.Flush(); 
       sw.Close(); 
      } 

      MessageBox.Show("Rows replaced: " + String.Join("; ", rows_replaced.ToArray()) + " .\nRows not replaced: " + String.Join("; ", rows_not_replaced.ToArray()) + ".\nComplete."); 
     } 
    } 

다음 코드는 4, 1로 바꿉니다. 7, 5; 13, 11; 행이 각각 9 번째 항목 인 경우 행이 올바르게 논리를 이해합니다.

+0

다음은 [link] (https://onedrive.live.com/#cid=59802AFBA7F9048E&id=59802AFBA7F9048E%21110)입니다. 프로젝트를 다운로드 할 수 있습니다. 코드를 테스트하십시오. WindowsFormsApplicationHelp1이라는 아카이브. – Wallstrider

+0

@Wallstrider .... 도움을 주셔서 대단히 감사합니다. 그것은 완벽하게 작동합니다. 또 다른 한가지는 각 줄의 9 번째 항목 (큰 텍스트 파일 인 경우를 의미하는 !!!)을 기준으로 어느 줄을 바꿔야하는지 모르는 경우입니다. 또 다시 고마워요........... 해결책과 함께 내 문제에 대해 생각할 수있는 또 다른 방법이 있습니다. 감사합니다. – islat

0

그냥 교체 :

if (SplitText[9] == SplitData[9] && SplitText[11] == null) 

하려면를 :

if (SplitText[9] == SplitData[9] && SplitText[11] == String.Empty) 

당신이 공유 한 파일 내의 모든 상황에서 SplitText [11]이 null이되지 않기 때문입니다.

관련 문제