2016-12-28 145 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

正如我之前提到的评论,我使用不同的字节数组和不同的文件名称..这就是为什么我对它感到困惑 –