Open files in own applications c# winform

61 Views Asked by At

I was asked to create a program that opens any file with their associated applications (eg. docx in word, txt in notepad, etc). This is my code:

            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                foreach (string path in ofd.FileNames)
                {
                    FileInfo fi = new FileInfo(path);
                    ListViewItem lvi = new(fi.Name);
                    lvi.SubItems.Add(path);
                    listView1.Items.Add(lvi);

                    System.Diagnostics.Process.Start(@"c:\textfile.txt");
                    System.Diagnostics.Process.Start(@"c:\image.jpg");
                    System.Diagnostics.Process.Start(@"c:\document.pdf");
                }

However, this error constantly occurs

System.ComponentModel.Win32Exception: 'An error occurred trying to start process 'c:\textfile.txt' with working directory \bin\Debug\net6.0-windows'. The system cannot find the file specified.'

I am using c# WinForms. The selected files can be displayed into the listview control without any issues if the system.diagnostics.process.start wasn't included. But what I really need is for the files to pop up and display while in their default applications

I have tried

            string exeDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            Directory.SetCurrentDirectory(exeDir);

but I don't think that the working directory is the problem

EDIT:

I tried the Process.Start.Info class

                            foreach (var dir in Directory.GetFiles(@"C:\"))
                    {
                        ProcessStartInfo psi = new ProcessStartInfo(dir);
                        psi.WindowStyle = ProcessWindowStyle.Maximized;
                        Process.Start(psi);
                    }

and the error changed from

The system cannot find the file specified.'*

to

The specified executable is not a valid application for this OS platform.'

0

There are 0 best solutions below