이 프로그램을 작성하면 증분 번호가있는 txt 파일을 생성 할 수 있지만 각 파일 일련 번호는 txt 파일 내부에 쓰기를 원합니다. 그 자체.txt 파일을 열고 처음 두 줄의 텍스트 바꾸기 (C#)
예 : Mytext-000001.txt, Mytext-000002.txt, Mytext-000003.txt의 세 파일을 생성했으며 첫 번째 줄에는 "Hello 000000"이 포함되어 있고 두 번째 줄에는 "My number is 000000 ", 이제 각 txt 파일을"Hello "+ 명명 된 증분 번호가 포함되도록 변경하려고합니다.
그래서 각 파일의 출력은 다음과 같습니다
Mytext-000001.txt,
Hello 000001
My number is 000001
Mytext-000002.txt,
Hello 000002
My number is 000002
Mytext-000003.txt,
Hello 000002
My number is 000003
내 코드
string path = System.IO.Path.GetDirectoryName(Application.ExecutablePath) + @"\path.txt";
string pth_input = null;
string pth_output = null;
using (StreamReader sx = File.OpenText(path))
{
pth_input = sx.ReadLine();
pth_output = sx.ReadLine();
}
Console.WriteLine("Number of Files?");
string number_of_files = Console.ReadLine();
int get_number_of_files = Int32.Parse(number_of_files) + 1;
string PathFiletoCopy = pth_input;
string Extension = System.IO.Path.GetExtension(PathFiletoCopy);
string PartialNewPathFile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(PathFiletoCopy), System.IO.Path.GetFileNameWithoutExtension(PathFiletoCopy) + "-");
for (int i = 1; i < get_number_of_files; i++)
{
System.IO.File.Copy(PathFiletoCopy, PartialNewPathFile + i.ToString("D6") + Extension);
}
string[] txtfiles = Directory.GetFiles(pth_output, "*.txt");
foreach (var file in txtfiles)
{
string get_file_counter = System.IO.Path.GetDirectoryName(file.Substring(7,6));
FileStream fs = new FileStream(file, FileMode.Append, FileAccess.Write);
FileStream fi = new FileStream(file, FileMode.Open, FileAccess.Read);
using (StreamReader reader = new StreamReader(fi))
{
using (StreamWriter writer = new StreamWriter(fs))
{
string line = null;
while ((line = reader.ReadLine()) != null)
{
string replace_line_one = line.Replace("Hello 000001","Hello"+ "["+get_file_counter+"]");
string replace_line_two = line.Replace("My number is 000001", "My number is" + "[" + get_file_counter + "]");
}
writer.Close();
} reader.Close();
}
}
Console.Read();
난 당신이
당신의 도움에들 감사합니다 도움이 될 수 있습니다 희망
이미 코드를 작성한 것처럼 보입니다. 실제 문제는 무엇입니까? 당신은 당신의 코드를 게시하는 것에 대해 칭찬을 받아야하지만, 그 문제는 무엇입니까? –
안녕하세요, 내가 받고있는 오류는 다른 프로세스에서 사용 중이기 때문에 파일에 액세스 할 수 없다는 것입니다. – user1848210
'FileReadAllLines()'; 원하는대로 교체하십시오. 'FileWriteAllLines()' – Plutonix