Rocklee Rocklee - 1 month ago 16
C# Question

C#: Attach a custom file (.sl) to an email

I am trying to attach a custom file to an email with no avail. The below code calls a batch file which creates an encrypted file and then i try to attach that file to an email. The batch file creates the file successfully but when it tries to attach it says that the file does not exist. I read that you need to create a memory buffer or attach to same thread, i tried thinkering with it but i am really stumped right now. Can anyone assist?

Code:

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);


Error:


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)


Thanks!

Answer

The exception is pretty clear. It means that the file did not exist at the moment the attachment was created. I would modify your code:

  1. Wait util process exit. Without it you create an attachment before the batch file creates it.
  2. Check for exit code (if your batch supports it)
  3. Check for file before create attachment to handle the situation when batch did not create a file for some reason.