[C#] txt파일 일부분 내용 수정
abcdefg
이 파일을 읽어서 일부분을 수정하는 다음과 같은 코드를 작성합니다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
FileStream fs = new FileStream("Data.txt", FileMode.Open, FileAccess.ReadWrite);
fs.Seek(6, SeekOrigin.Begin);
fs.Write(new byte[] { 65, 66 }, 0, 2);
fs.Close();
}
}
}
코드를 실행하고 나면, 테스트 파일의 내용이 다음과 같이 수정됩니다.
abcABfg
방법2:
string key;
StreamReader sr1 = new StreamReader(configfile,Encoding.GetEncoding("euc-kr"));
string buf = sr1.ReadToEnd();
이렇게 파일 열구 다 읽은다음에요
sr1.BaseStream.Position = 0;
다시 맨위치로 옮기구
while (sr1.EndOfStream == false)
{
key = sr1.ReadLine();
한줄씩 읽으면서 444가 있는걸 Contains함수를 이용해서 찾아요
bool abc=key.Contains("444");
if(abc==true)
{
내용이 있는 줄이면 전체 파일 내용을 옮겼던 string중에서 offset을 찾고
지운 다음에 새롭게 바뀐 내용 string 변수를 insert함수를 이용해 집어넣는 거죠
int offset = buf.indexof(key,0);
buf = buf.Remove(offset,key.Length);
key= key.Replace("444","777");
buf = buf.Insert(offset,key);
}
}
sr1.close();
그리고 StreamWriter로 다시 열어서 파일에 써요
StreamWriter sr1 = new StreamWriter(configfile,Encoding.GetEncoding("euc-kr"));
sr1.write(buf);
sr1.close();