Carlos Miguel Salamat Carlos Miguel Salamat - 3 months ago 20
C# Question

how to use a variable from other context in c#

I just need to know on how to use variable from other blocks or context(or whatever they call it)...

I was trying to create an app installer for windows 10 using powershell but i'm just a beginner for c#...

I have 2 Buttons the browse and install, I declare the location of the file in the browse button's block and I was trying to use that variable in the install button's context.

But all I got is "The name "appFile" does not exist in the current context."

Here's my code:

private void button3_Click(object sender, EventArgs e)
{
MessageBox.Show("Created by Carlos Miguel Salamat","Windows App Installer");
}

private void button1_Click(object sender, EventArgs e)
{

OpenFileDialog file = new OpenFileDialog();
file.Title = "Choose Package File";
file.InitialDirectory = @"c:\";
file.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
file.FilterIndex = 2;
file.RestoreDirectory = true;
if (file.ShowDialog() == DialogResult.OK)
{
textBox1.Text = file.FileName;

string appFile = file.FileName;
}
}
private void button2_Click(object sender, EventArgs e)
{
string strCmdText;
strCmdText = "powershell.exe add-appxpackage";
System.Diagnostics.Process.Start("CMD.exe", strCmdText, appFile);
}
}
}


`

Answer

Define it to global,

string appFile = "";

private void button1_Click(object sender, EventArgs e)
{

    OpenFileDialog file = new OpenFileDialog();
    file.Title = "Choose Package File";
    file.InitialDirectory = @"c:\";
    file.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
    file.FilterIndex = 2;
    file.RestoreDirectory = true;
    if (file.ShowDialog() == DialogResult.OK)
    {
        textBox1.Text = file.FileName;

        this.appFile = file.FileName;
    }
}
private void button2_Click(object sender, EventArgs e)
{
    string strCmdText;
    strCmdText = "powershell.exe add-appxpackage";
    System.Diagnostics.Process.Start("CMD.exe", strCmdText, this.appFile);
}

Hope helps,