2014-01-30 3 views
1

은 단순히 특정 디렉토리에있는 모든 텍스트 파일을 병합 할, 다음 명령 프롬프트 명령과 유사한 : 나는 다음과 같은 코드를 작성했습니다여러 텍스트 파일 병합 - 하나의 파일을 쓰지 않는 StreamWriter?

cd $directory 
copy * result.txt 

거의 내가 원하는 것을 달성하는, 그러나 그것은 이상한 일을하고 있어요 . StreamWriter이 첫 번째 파일을 쓸 때 (또는 i = 0 일 때) 실제로 내용을 쓰지 않습니다. 첫 번째 파일이 ~ 300KB 임에도 불구하고 파일 크기는 0 바이트로 유지됩니다. 그러나 다른 파일 쓰기가 성공적으로 실행됩니다.

명령 프롬프트의 출력을 diff의 C# 코드 출력과 비교하면 큰 텍스트 블록이 없음을 알 수 있습니다. 또한 명령 프롬프트 결과는 C# 결과가 700KB 인 1,044KB입니다.

string[] txtFiles = Directory.GetFiles(filepath); 
using (StreamWriter writer = new StreamWriter(filepath + "result.txt")) 
{ 
    for (int i = 0; i < txtFiles.Length; i++) 
    { 
     using (StreamReader reader = File.OpenText(txtFiles[i])) 
     { 
      writer.Write(reader.ReadToEnd()); 
     } 
    } 
} 

오전 내가 잘못 StreamWriter/StreamReader를 사용하고 계십니까?

답변

1

여기가 도움이되기를 바랍니다. 참고 : 스트림에서 다른 스트림으로 복사하면 일부 RAM이 절약되어 성능이 크게 향상됩니다. 바이트를 읽고을 쓰는 대신 읽기 위해 스트림을 사용하여

class Program 
{ 
    static void Main(string[] args) 
    { 
     string filePath = @"C:\Users\FunkyName\Desktop"; 
     string[] txtFiles = Directory.GetFiles(filePath, "*.txt"); 

     using (Stream stream = File.Open(Path.Combine(filePath, "result.txt"), FileMode.OpenOrCreate)) 
     { 
      for (int i = 0; i < txtFiles.Length; i++) 
      { 
       string fileName = txtFiles[i]; 
       try 
       { 
        using (Stream fileStream = File.Open(fileName, FileMode.Open, FileAccess.Read)) 
        { 
         fileStream.CopyTo(stream); 
        } 
       } 
       catch (IOException e) 
       { 
        // Handle file open exception 
       } 
      } 
     } 
    } 
} 
+0

'FileMode.OpenOrCreate'는 프로그램이 같은 디렉터리에서 다시 실행될 때 모든 파일을 출력 파일에 두 번째로 추가합니다. 그것을 완전히 덮어 쓰려면'FileMode.Create'를 사용하거나, 이미 존재할 때 예외를 얻으려면'FileMode.CreateNew'를 사용하십시오. – Herdo

+0

@Herdo 프로그램은 실행되기 전에'filePath' 변수와 일치하는 기존 폴더를 삭제하므로이 구현은 정상적으로 이루어져야합니다. 고맙습니다! – TimeBomb006

1

최소한의 구현, - 유의하시기 바랍니다, 당신이 잘못된 행동 피하기 위해 올바르게 IOException가 처리해야 : 난 당신의 코드를 작성

var newline = Encoding.ASCII.GetBytes(Environment.NewLine); 
var files = Directory.GetFiles(filepath); 
try 
{ 
    using (var writer = File.Open(Path.Combine(filepath, "result.txt"), FileMode.Create)) 
     foreach (var text in files.Select(File.ReadAllBytes)) 
     { 
      writer.Write(text, 0, text.Length); 
      writer.Write(newline, 0, newline.Length); 
     } 
} 
catch (IOException) 
{ 
    // File might be used by different process or you have insufficient permissions 
} 
0

을, 제대로 작동합니다! 내가 그것을 다른 폴더에 저장되어 있기 때문에 파일을 볼 수 없습니다 생각

using (StreamWriter writer = new StreamWriter(filepath + "/result.txt")) 

:

using (StreamWriter writer = new StreamWriter(filepath + "result.txt")) 

에 : 만 라인을 변경할 수 있습니다.

관련 문제