2013-01-23 2 views
0

Readread 모드에서 열린 streamreader를 사용하여 파일을 읽습니다. 필자가 가지고있는 요구 사항은 특정 텍스트 파일을 확인하고 발견 된 경우 해당 줄을 새 줄로 바꾸는 것입니다.쓰기 중 파일의 라인을 덮어 쓰기

현재 나는 쓰기 위해 StreamWriter을 초기화했습니다.

파일에 텍스트를 쓰고 있지만 새 줄에 추가하고 있습니다.

그래서 특정 줄 텍스트를 바꾸려면 어떻게해야합니까?

System.IO.FileStream oStream = new System.IO.FileStream(sFilePath, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.Read); 
System.IO.FileStream iStream = new System.IO.FileStream(sFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite); 

System.IO.StreamWriter sw = new System.IO.StreamWriter(oStream); 
System.IO.StreamReader sr = new System.IO.StreamReader(iStream); 

string line; 
int counter = 0; 
while ((line = sr.ReadLine()) != null) 
{ 
    if (line.Contains("line_found")) 
    { 
     sw.WriteLine("line_found false"); 
     break; 
    } 
    counter++; 
} 
sw.Close(); 
sr.Close(); 
+2

코드에 질문을 붙여주십시오. – Matt

답변

3

안녕 그것은 당신을 도울 것입니다 .... 코드 아래를보십시오 ....

// ... 텍스트 파일의 모든 HI를 교체

var fileContents = System.IO.File.ReadAllText(@"C:\Sample.txt"); 

fileContents = fileContents.Replace("Hi","BYE"); 

System.IO.File.WriteAllText(@"C:\Sample.txt", fileContents); 

// 특정 줄에 HI 바꾸기 ...

 string[] lines = System.IO.File.ReadAllLines("Sample.txt"); 
     for (int i = 0; i < lines.Length; i++) 
     { 
      if(lines[i].Contains("hi")) 
      { 
       MessageBox.Show("Found"); 
       lines[i] = lines[i].Replace("hi", "BYE"); 
       break; 
      } 
     } 
     System.IO.File.WriteAllLines("Sample.txt", lines); 
+0

"Hi"와 일치하는 모든 내용을 "BYE"로 바꿀 것입니다. 제 요구 사항은 특정 줄의 텍스트를 대체하는 것입니다. 가능한가? – user987316

+0

필요한 코드를 추가했습니다 ... 지금 시도하십시오 .... – Pandian

+0

답변 해 주셔서 감사합니다. – user987316