简体   繁体   中英

Open a PDF file with c#

I'm working on a C # application that automatically opens a PDF file when I press a button on a windows form.

Here is my code:

 System.Diagnostics.Process.Start(@"Stock\171457\money.pdf");

It works perfectly. But in this case I already know the name of the file money.pdf to open. But for example if I want to open a file with a different name that I do not know? That is, I want to open the file independently of its name.

I would assume the pdf files are available under the directory/folder "Stock\\171457\\" or you would at least need to know the location of the pdf files that you want to open. 1. So first get all the list of all the pdf files names from the folder.

private string[] pdfFiles = Directory.GetFiles("C:\\Documents", "*.pdf")
                                     .Select(Path.GetFileName)
                                     .ToArray();
  1. Call the start method with the file name from the previous step.

i thought of something like this:

// create baspath for the search
string basepath = Path.Combine(Application.StartupPath, "Stock", "171457");
// getting the files form th OS
string[] allfiles = System.IO.Directory.GetFiles(basepath, "*.pdf", System.IO.SearchOption.AllDirectories);
// security check, since it will open all files
if (MessageBox.Show($"You are going to open {allfiles.Count()} files. Continue?","",MessageBoxButtons.OKCancel) == DialogResult.OK)
{
    foreach (var item in allfiles)
    {
        System.Diagnostics.Process.Start(item);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM