Martijn
Martijn

Reputation: 24799

C# Process object doesn't open PDF

I am creating dynamically a PDF file. After creating I want to open the pdf file. For that I am using this code:

    System.Diagnostics.Process p = new System.Diagnostics.Process();
    p = new System.Diagnostics.Process();

    p.StartInfo.FileName = CreatePDF(); // method that creats my pdf and returns the full path

    try
    {
        if (!p.Start())
            Controller.Error = "Opening acrobat failed..";
    }
    catch(Exception ex)
    {
        Controller.Error = "Create PDF::" + ex.Message;
    }

When executing this code, nothing happens and I don;t get any errors. What am I doing wrong?

Upvotes: 0

Views: 4537

Answers (3)

Martin Peck
Martin Peck

Reputation: 11564

It's not clear to me whether this is an ASP.NET app or Winforms. If Winforms then...

using (Process p = new Process())
{
    p.StartInfo.RedirectStandardOutput = false;
    p.StartInfo.FileName = @"C:\foo.pdf";
    p.StartInfo.UseShellExecute = true;
    p.Start();
    p.WaitForExit();             
}

... will work fine.

If this is ASP.NET MVC then you should look at the FileResult type and the File method of Controller...

public ActionResult GetFile()
{
    return File("foo.pdf", "application/pdf");
}

... as this is exactly what this is for.

Upvotes: 0

mhenrixon
mhenrixon

Reputation: 6278

Asp.net? What I would do is to take the memory stream and write it to the response stream like follows:

Response.ContentType = "application/pdf"; 
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", file.FileName)); 
Response.BinaryWrite(file.FileBytes); 
Response.Flush(); 
Response.End();

For windows forms I'd take a look at using Foxit Reader instead. I have a blog post about printing directly from foxit. You can open similarly.

EDIT: To create an attachment you add a reference to System.Net.Mail and do something like:

var stream = GetTheFileAsStream();
var attachment = new Attachment(stream);

Upvotes: 2

Jose Basilio
Jose Basilio

Reputation: 51498

UPDATE:

Since this is an ASP.NET app, this code will not work. It cannot interact with the desktop of the server hosting ASP.NET.

If the intention is to display the PDF for the users accessing from a browser, then the code for that is completely different.

Upvotes: 2

Related Questions