Martin Toro
Martin Toro

Reputation: 3

Get the path of the file that launched my app

I'm working in my own PDF Reader using C# & Patagames/PDFium library and I am able to open files using "OpenFileDialog" and show them on the screen. However, due requirements of the boss I am not allowed to have any buttons in the screen. All we want is to click the any .PDF file (For example, in this route: C:\Users\Adaptabilidad\Desktop\Test.pdf) and launch it & show the PDF document directly, without looking for the directory of the file. I've set my ".exe" as default app, although, the PDF Reader is executed no PDF file is displayed.

I've tried Application.ExecutablePath, Application.StartUpPath after initializing the component and I'm still getting the route of my PDF reader executable (.Exe) but I need to know what the file to be open is (filepath).

How can I get the information about the .pdf file (directory can vary) that is launching my app? You can see my code below if helps.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Patagames;
using System.IO;

namespace aPDF
{
    public partial class Form1 : Form
    {
        public Form1()
         {
            InitializeComponent();
         }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "PDF Files (*.pdf)|*.pdf";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                openfile(dialog.FileName);
             }
         }
        public void openfile(string filepath)
        {
            byte[] bytes = System.IO.File.ReadAllBytes(filepath);
            var stream = new MemoryStream(bytes);
            Patagames.Pdf.Net.PdfDocument pdfDocument = Patagames.Pdf.Net.PdfDocument.Load(stream);
            pdfViewer1.Document = pdfDocument;  
        }
    }
}

Updates:

I've found a way. One of you guys that commented allowed me to find out how to do it.

What I used is the following sentence in my Program.cs:

public static string[] cmdLine = Environment.GetCommandLineArgs();
public static string cmd = cmdLine[1];

Then, y use "cmd" as filepath.

Why? Environment.GetCommandLineArgs(); returns 2 values, the .exe you're executing (your program) & as second value the file that you've used in order to launch that .exe.

That's it. Thank you for your answers.

Upvotes: 0

Views: 337

Answers (0)

Related Questions