19GreenBlankets
19GreenBlankets

Reputation: 95

How to make 2 process access the same path?

I'm using c#. I'm receiving an error about a path is currently accessed by other processes. What my system is trying to do is to access the path: @"C:\temps\" + client_ids + "_" + rown + ".pdf" and use the same path for attachment before sending it to client's email.

here's what I've done so far. I comment out some of my code because I'm not sure what to do.

FileStream fs = null;
using (fs = new FileStream(@"C:\\temps\\" + client_ids + "_" + 
rown + ".pdf", 
FileMode.Open,FileAccess.Read,FileShare.ReadWrite))
{
    TextReader tr = new StreamReader(fs);                  
    //report.ExportToDisk
    //(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat,tr);
    //report.Dispose();
    //Attachment files = new Attachment(tr);
    //Mailmsg.Attachments.Add(files);
    //Clients.Send(Mailmsg);
}

Upvotes: 1

Views: 82

Answers (2)

John
John

Reputation: 829

You cannot attach a file to an email if that file is open. You must close (save) the file first.

While @ali answer is technically correct, it is unnecessary. Why go through the overhead of creating a copy of the file which then needs to be deleted, etc.?

Assuming I understand what you are trying to do correctly, simply move your code for mail to after the file is successfully created and saved. And, I don't think you need the overhead of either the filestream or the textreader. As long as your report object can save the file to disk someplace, you can attach that file to your email message and then send it.

While I do not claim to know anything about how Crystal Decisions handles exports, etc. Perhaps something like this would work:

(I got this code from: https://msdn.microsoft.com/en-us/library/ms226036(v=vs.90).aspx)

private void ExportToDisk (string fileName)
{
   ExportOptions exportOpts = new ExportOptions();
   DiskFileDestinationOptions diskOpts =
      ExportOptions.CreateDiskFileDestinationOptions();

   exportOpts.ExportFormatType = ExportFormatType.RichText;
   exportOpts.ExportDestinationType =
      ExportDestinationType.DiskFile;

   diskOpts.DiskFileName = fileName;
   exportOpts.ExportDestinationOptions = diskOpts;

   Report.Export(exportOpts);
}

You will need to change the ExportFormatType property.

Then, simply attach the file to your email and send:

Attachment Files = new Attachment(filename);
Mailmsg.Attachments.add(files);
Clients.Send(Mailmsg);

Upvotes: 0

Ali Faris
Ali Faris

Reputation: 18592

you can make temp copy of file before you use it in mail attachment and then use the copy instead of the original file

Upvotes: 4

Related Questions