2016-10-31 3 views
-1

이 프로그램을 작성하면 증분 번호가있는 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(); 

난 당신이

당신의 도움에들 감사합니다 도움이 될 수 있습니다 희망

+2

이미 코드를 작성한 것처럼 보입니다. 실제 문제는 무엇입니까? 당신은 당신의 코드를 게시하는 것에 대해 칭찬을 받아야하지만, 그 문제는 무엇입니까? –

+0

안녕하세요, 내가 받고있는 오류는 다른 프로세스에서 사용 중이기 때문에 파일에 액세스 할 수 없다는 것입니다. – user1848210

+0

'FileReadAllLines()'; 원하는대로 교체하십시오. 'FileWriteAllLines()' – Plutonix

답변

0
string[] files = Directory.GetFiles(directoryPath, "*.txt"); 
Regex regex = new Regex("\\d+(?=\\.txt)"); 

foreach (var file in files) 
{ 
    string[] lines = File.ReadAllLines(file); 
    string number = regex.Match(Path.GetFileName(file)).Value; 

    lines[0] = "Hello " + number; 
    lines[1] = "My number is " + number; 

    File.WriteAllLines(file, lines); 
} 

정규식은이 솔루션을 비특이적으로 만듭니다.

+0

정말 고마워, 이거 해결해! – user1848210

0

이것은 당신이 모든 TXT 파일이 들어있는 폴더의 경로를 당길 수 기대하고 myDir에서 당신

System.IO.Directory myDir = pth_output; 
int count = (myDir.GetFiles().Length) + 1; 
string thenumber = String.Format("0:000000", count); 
string filename = "Mytext-" + thenumber + ".txt"; 
string filetext = "Hello " + thenumber + Environment.NewLine + "My number is " + thenumber; 
File.WriteAllText(Path.Combine(myDir,filename) , createText); 

을 위해 트릭을 할 수 있습니다. 당신에게 파일의 수를 줄 것이다

myDir.GetFiles().Length 폴더에 존재하는 우리는 TXT 파일을 원하는대로 당신은 이전 제로의 당신의 형식으로 당신에게 수를 줄 것이다 Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories).Length; 대신

String.Format("0:000000", count);

처럼 검색 할 수 있습니다.

+0

고마워요.이 파일도 작동합니다! – user1848210

+0

@ user1848210 도와 드리겠습니다. 감사의 말을하는 또 다른 방법은 대답을 upvote 수 있습니다. –

관련 문제