2016-11-06 93 views
0

我試圖將一個自定義文件附加到電子郵件沒有用。下面的代碼調用創建加密文件的批處理文件,然後嘗試將該文件附加到電子郵件。該批處理文件成功創建文件,但是當它試圖附加時說該文件不存在。我讀過,你需要創建一個內存緩衝區或附加到相同的線程,我試着用它思考,但我現在真的很難過。任何人都可以協助C#:將一個自定義文件(.sl)附加到一個電子郵件

代碼:

   string file = @"C:\EncryptedFile\file.sl"; 

       //EXECUTE BATCHFILE SUPPLYING PARAMETERS TO IT 
       Process process = new Process(); 
       process.StartInfo.Arguments = string.Format("{0} {1} {2} {3}", 
              file, 
              key, 
              doc1, 
              doc2); 
       process.StartInfo.FileName = MyBatchFile; 
       process.StartInfo.UseShellExecute = false; 
       process.StartInfo.CreateNoWindow = true; 
       process.Start(); 

       //attach to email 
       Attachment attachment; 
       attachment = new Attachment(file); 
       mail.Attachments.Add(attachment); 

錯誤:

System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\EncryptedFile\file.sl'. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share) at System.Net.Mail.AttachmentBase.SetContentFromFile(String fileName, String mediaType) at System.Net.Mail.AttachmentBase..ctor(String fileName) at System.Net.Mail.Attachment..ctor(String fileName)

謝謝!

+0

通過將調試點(暫停批處理文件執行)檢查到附件代碼被調用時文件已存在嗎? 也,我會建議創建兩個批處理文件。一個是創建該文件,另一個是將其附加到郵件中。您可以在第一個批處理文件執行結束時調用第二個批處理文件,等待文件沒有正確創建。 –

回答

1

這個例外很明顯。這意味着該文件在附件創建時不存在。 我會修改你的代碼:

  1. 等待util進程退出。沒有它,你可以在批處理文件創建之前創建一個附件。
  2. 檢查退出代碼(如果您的批處理支持它)
  3. 在創建附件前檢查文件,以處理批處理由於某種原因未創建文件時的情況。
+0

你會提供一些代碼來展示如何做到這一點? – Prisoner

+0

嘿謝謝你,第一個人更容易實現,它的工作。我只需要放置一個process.WaitForExit();在添加附件之前,它工作!我會將你的評論標記爲答案,但我沒有足夠的代表。 – Raidenlee

+0

你知道如何做一個「等待」郵件發送()完成然後繼續嗎?我試圖刪除發送郵件後的加密文件,但我得到一個「文件正在使用」錯誤(很明顯,我試圖刪除該文件,而郵件正在使用它,所以我需要等待或者其他的東西)。 – Raidenlee

相關問題