Pranav Jituri
Pranav Jituri

Reputation: 823

Access Denied When Running Command Using PowerShell in C#

I am trying to write a program to export the System Info using the Msinfo32 utility on a button click. I am doing this in the C# using the Powershell class. Now, the thing is that the compiled application is already set to run with Administrator Privileges. But, I am still getting the Access Denied Error when the utility starts saving to Desktop. Below is the Source Code :-

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 System.Management.Automation;
using System.IO;
using System.Management.Automation.Runspaces;
using System.Collections.ObjectModel;

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

        private void button1_Click(object sender, EventArgs e)
        {
            progressBar1.Value = 10;
            Runspace Run = RunspaceFactory.CreateRunspace();
            Run.Open();
            progressBar1.Value = 30;
            Pipeline pipeline = Run.CreatePipeline();
            progressBar1.Value = 50;
            Command Msinfo32 = new Command("Msinfo32.exe");
            string path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            Msinfo32.Parameters.Add("/nfo");
            Msinfo32.Parameters.Add(path);
            progressBar1.Value = 70;
            pipeline.Commands.Add(Msinfo32);
            pipeline.Invoke();
            pipeline.Stop();
            Run.Close();
            progressBar1.Value = 100;
            MessageBox.Show("The Task Has Completed Successfully");


    }


}
}

Could anyone please tell what is happening wrong?

Upvotes: 0

Views: 934

Answers (1)

Ryan Bemrose
Ryan Bemrose

Reputation: 9266

You're getting access denied because you're telling msinfo to write data directly to the Desktop directory itself, and not to a file.

Your 'path' variable contains the name of the Desktop directory. You need to append a filename to this parameter. eg:

OLD: MSinfo32.Parameters.add(path)

NEW: MSinfo32.Parameters.add(path + "\\foo.txt")

Upvotes: 1

Related Questions