samsam114
samsam114

Reputation: 977

how to open a file such as pdf,etc "from" a windows form app in C#

I want to create a windows form containing a linklable such that when user clicks on that linklable, a file with some format(for example a pdf file or html file) which is added to resources,opens. it will not be opened in form,it means the file will be opened out of program with adobe reader or another program. How can I do this? Thank you

Upvotes: 4

Views: 3904

Answers (2)

Dirk Vollmar
Dirk Vollmar

Reputation: 176269

You can do so using Process.Start:

System.Diagnostics.Process.Start(@"C:\myfolder\document.pdf");

If the file is an embedded resource, you would first have to extract it and save it to disc. You cannot open a document from a stream directly, because third-party applications won't be able to access your process' memory:

string resourceName = "test.pdf";
string filename = Path.Combine(Path.GetTempPath(), resourceName);

Assembly asm = typeof(Program).Assembly;
using (Stream stream = asm.GetManifestResourceStream(
    asm.GetName().Name + "." + resourceName))
{
    using (Stream output = new FileStream(filename, 
        FileMode.OpenOrCreate, FileAccess.Write))
    {
        byte[] buffer = new byte[32 * 1024];
        int read;
        while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
        {
            output.Write(buffer, 0, read);
        }
    }
}
Process.Start(filename);

Upvotes: 3

Anton Gogolev
Anton Gogolev

Reputation: 115877

You'll have to extract this file from resources (I'm assuming we're talking assembly-embedded resources here) to %temp% and then just Process.Start() it. Make sure extracted file has proper extension, though.

Upvotes: 5

Related Questions