2017-02-06 1 views
0

nQuant을 사용하여 폴더의 모든 png를 8bpp png로 변환하려고합니다. 다음 코드를 사용해 보았습니다.동일한 FileStream에서 읽기 및 쓰기

foreach (string file in Directory.GetFiles(tempFolderPath, "*.png", SearchOption.TopDirectoryOnly)) 
     { 
      using (MemoryStream memory = new MemoryStream()) 
      { 
       using (FileStream fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.ReadWrite)) 
       { 
        using (Bitmap image = new Bitmap(fs)) 
        { 
         using (Image quantized = quantizer.QuantizeImage(image)) 
         { 
          quantized.Save(memory, ImageFormat.Png); 
          byte[] bytes = memory.ToArray(); 
          fs.Write(bytes, 0, bytes.Length); 
         } 
        } 
       } 
      } 
     } 

그러나 이것은 작동하지 않습니다. 예외 없음. 단지 파일에 쓰지 않습니다. 나는이 작업 코드로 바꿨다.

Bitmap image; 
foreach (string file in Directory.GetFiles(tempFolderPath, "*.png", SearchOption.TopDirectoryOnly)) 
     { 
      using (FileStream fso = new FileStream(file, FileMode.Open, FileAccess.ReadWrite)) 
      { 
       image = new Bitmap(fso); 
      } 

      using (MemoryStream memory = new MemoryStream()) 
      { 
       using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.ReadWrite)) 
       { 
        using (Image quantized = quantizer.QuantizeImage(image)) 
        { 
         quantized.Save(memory, ImageFormat.Png); 
         byte[] bytes = memory.ToArray(); 
         fs.Write(bytes, 0, bytes.Length); 
        } 
       } 
      } 
     } 

는 둘 중 하나만을 할 수 FileMode.OpenOrCreate처럼 보인다.

어쨌든 읽고 쓸 수 있습니까? FileStream?

+0

다음과 같은 'C# Stackoverflow 읽기 및 동일한 FileStream에 쓰기'에 대한 Google 검색을 수행합니다. – MethodMan

+0

@MethodMan 예 [this] found (http://stackoverflow.com/questions/605685/how-to-both-read -and-c-sharp-a-file-in-c-sharp)를 사용했고, 가장 큰 대답을 사용했습니다. 나는 또한 [이] (http://stackoverflow.com/questions/33633344/read-and-write-to-a-file-in-the-same-stream)을 발견하고 fs.Flush()를 추가하려고했지만 또한 작동하지 않았다. – I23BigC

답변

1

파일 스트림에서 위치를 재설정하지 않으므로 코드가 이러한 이미지의 콘텐츠를 하나의 파일로 연결합니다.

하지만 하나의 스트림을 사용하는 것은 좋지 않습니다. 새 파일이 old보다 작 으면 파일 크기가 더 작은 크기로 조정되지 않으므로 결과가 깨집니다.

대신 임시 파일을 사용하십시오.