2016-12-28 282 views
0

我試圖用File.WriteAllBytes()保存多個圖像,即使在我試圖單獨保存與'Thread.Sleep()'它不工作..使用File.WriteAllBytes保存多個圖像只保存最後一個

我的代碼:

 byte[] signatureBytes = Convert.FromBase64String(model.Signature); 
     byte[] idBytes = Convert.FromBase64String(model.IdCapture); 

     //Saving the images as PNG extension. 
     FileManager.SaveFile(signatureBytes, dirName, directoryPath, signatureFileName); 
     FileManager.SaveFile(idBytes, dirName, directoryPath, captureFileName); 

SAVEFILE功能:

public static void SaveFile(byte[] imageBytes, string dirName, string path, string fileName, string fileExt = "jpg") 
    { 
     if (!string.IsNullOrEmpty(dirName) 
      && !string.IsNullOrEmpty(path) 
      && !string.IsNullOrEmpty(fileName) 
      && imageBytes.Length > 0) 
     { 
      var dirPath = Path.Combine(path, dirName); 

      var di = new DirectoryInfo(dirPath); 

      if (!di.Exists) 
       di.Create(); 

      if (di.Exists) 
      { 
       File.WriteAllBytes(dirPath + [email protected]"\{fileName}.{fileExt}", imageBytes); 
      } 
     } 
     else 
      throw new Exception("File cannot be created, one of the parameters are null or empty."); 
    } 
+1

*不工作*是什麼意思?你是否遇到異常? – MarcinJuraszek

+1

Yea只能基於此代碼示例進行猜測,但也許您正在重複使用兩個調用的相同文件名 – BlakeH

+0

這些文件的名稱是不同的,沒有例外。只有在程序結束時保存1個文件的結果 –

回答

0

除了可能性(。由@Daniel),你覆蓋相同的文件中提到,我不知道這個代碼:

 var di = new DirectoryInfo(dirPath); 

     if (!di.Exists) 
      di.Create(); 

     if (di.Exists) 
     { 
      ... 
     } 

我會感到驚訝,如果,已經叫di.Create(),將Exists prope rty更新。事實上,它是不是更新 - 我檢查。

因此,如果目錄確實存在而不是,那麼即使在創建目錄後也不會輸入條件部分。這能解釋你的問題嗎?

+0

非常感謝,你是對.. –

2

File.WriteAllBytes():

「創建一個新文件,將指定的字節數組寫入文件,然後關閉該文件。如果目標文件已經存在,它被覆蓋」

由於expecify在: https://msdn.microsoft.com/en-ca/library/system.io.file.writeallbytes(v=vs.110).aspx

所以,如果你只能看到最後一個,要覆蓋文件

+0

正如我之前提到的評論,我使用不同的字節數組和不同的文件名稱..這就是爲什麼我對它感到困惑 –