How do I open a PDF included in my C# project in a browser window upon link click?

元气小坏坏 提交于 2021-02-05 11:34:26

问题


I have a folder in my project called "Guides" and have added "My Admin Guide.pdf".

The relevant xaml:

<TextBlock Margin="20,20,0,0" TextWrapping="Wrap">
    <Hyperlink x:Name="Documentation_Hyperlink" NavigateUri="/Guides/My Admin Guide.pdf" TargetName="_blank" RequestNavigate="Documentation_Hyperlink_RequestNavigate">
        Click Here for the Admin Guide
    </Hyperlink>
</TextBlock>

In the code-behind:

private void DDI_Documentation_Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
    Process.Start(e.Uri.ToString());
}

When I test, I get an exception "the system cannot find the file specified". I've verified e.Uri.ToString() has a value of /Guides/My Admin Guide.pdf. How do I do this properly?


回答1:


There is no easy as a link method to do the trick but the method once practiced is not so complicated. First of all assure yourself the PDF document is generated as an embedded resource. Then follow those steps :

Assembly assembly = Assembly.GetExecutingAssembly();
Stream stream = assembly.GetManifestResourceStream("{your_assembly_name}.{your_folder_and_file_name}");
FileInfo source = new FileInfo("{a_name_for_the_file}");
byte[] b;

using (BinaryReader br = new BinaryReader(stream))
{
  b = br.ReadBytes((int)stream.Length);
}
File.WriteAllBytes(source.FullName, b);

This will save the file into the user's computer, on the document, but the File will contain the path to open it easily. If you rather like the user don't have it on his computer you can "hide" it to a temp folder using System.IO.Path.GetTempPath() when you create the FileInfo.

Hope it can help you.



来源:https://stackoverflow.com/questions/62747361/how-do-i-open-a-pdf-included-in-my-c-sharp-project-in-a-browser-window-upon-link

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!