从ComboBox

时间:2017-01-17 18:26:04

标签: c# wpf combobox

C#非常新,所以全局变量对我来说仍然是一个谜和问题。

我试图使用Combobox创建一个动态变量,但它并不像我试图抛出它的任何东西。

我希望有人看到我的错误并告诉我我做错了什么。

我尝试将if语句放在各个位置,例如按钮单击和SelectedIndexChanged,但仍无法正常工作。

当我点击我的按钮运行脚本时,它说它找不到文件,ScriptName变量表示它没有在任何地方使用。

using System;
using System.Text;
using System.Windows.Forms;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.ComponentModel;
using System.Threading;
using System.IO;



namespace ServerStatusChecks
{
    public partial class Form1 : Form
    {
        private BackgroundWorker bw = new BackgroundWorker();
        public string ScriptName { get; set; }
        static string RunScriptResult;
        public Form1()
        {
            InitializeComponent();
            bw.WorkerReportsProgress = true;
            bw.WorkerSupportsCancellation = true;
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
        }


        private string LoadScript(string filename)
        {

            try
            {
                // Create an instance of StreamReader to read from our file.
                // The using statement also closes the StreamReader.
                using (StreamReader sr = new StreamReader(filename))
                {


                    // use a string builder to get all our lines from the file
                    StringBuilder fileContents = new StringBuilder();

                    // string to hold the current line
                    string curLine;

                    // loop through our file and read each line into our
                    // stringbuilder as we go along
                    while ((curLine = sr.ReadLine()) != null)
                    {
                        // read each line and MAKE SURE YOU ADD BACK THE
                        // LINEFEED THAT IT THE ReadLine() METHOD STRIPS OFF
                        fileContents.Append(curLine + "\n");
                    }

                    // call RunScript and pass in our file contents
                    // converted to a string
                    return fileContents.ToString();
                }
            }
            catch (Exception e)
            {
                // Let the user know what went wrong.
                string errorText = "The file could not be read:";
                errorText += e.Message + "\n";
                return errorText;

            }
        }

        public void button1_Click(object sender, EventArgs e)
        {

            if (bw.IsBusy != true)
            {
                bw.RunWorkerAsync();
            }
            // run our script and put the result into our textbox
            // NOTE: make sure to change the path to the correct location of your script

        }

        private void bw_DoWork(object sender, EventArgs e)
        {

            RunScriptResult = RunScript(LoadScript(ScriptName));
        }

        // Takes script text as input and runs it, then converts
        // the results to a string to return to the user
        private string RunScript(string scriptText)
        {
            get {
                return ScriptName;
            }
            set {
                if (comboBox1.SelectedIndex == 0)
                {
                    string ScriptName = @"c:\utils\Script1.ps1";
                }
                if (comboBox1.SelectedIndex == 1)
                {
                    string ScriptName = @"c:\utils\Script2.ps1";
                }
                if (comboBox1.SelectedIndex == 2)
                {
                    string ScriptName = @"c:\utils\Script3.ps1";
                }
            }
            // create Powershell runspace
            Runspace runspace = RunspaceFactory.CreateRunspace();

            // open it
            runspace.Open();

            // create a pipeline and feed it the script text
            Pipeline pipeline = runspace.CreatePipeline();
            pipeline.Commands.AddScript(scriptText);

            // add an extra command to transform the script output objects into nicely formatted strings
            // remove this line to get the actual objects that the script returns. For example, the script
            // "Get-Process" returns a collection of System.Diagnostics.Process instances.
            pipeline.Commands.Add("Out-String");

            // execute the script
            Collection<PSObject> results = pipeline.Invoke();

            // close the runspace
            pipeline.Dispose();
            runspace.Close();

            // convert the script result into a single string
            StringBuilder stringBuilder = new StringBuilder();
            foreach (PSObject obj in results)
            {
                stringBuilder.AppendLine(obj.ToString());

            }

            // return the results of the script that has
            // now been converted to text
            return stringBuilder.ToString();
        }

        // helper method that takes your script path, loads up the script
        // into a variable, and passes the variable to the RunScript method
        // that will then execute the contents
        private void Form1_Load(object sender, EventArgs e)
        {
            DirectoryInfo dinfo = new DirectoryInfo(@"C:\utils");
            FileInfo[] Files = dinfo.GetFiles("*.ps1");
            foreach (FileInfo file in Files)
            {
                comboBox1.Items.Add(file.Name);
            }
        }

        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            textBox1.Text = RunScriptResult;
        }
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            Thread.Sleep(1000);
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }

}

编辑: 工作脚本

using System;
using System.Text;
using System.Windows.Forms;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.ComponentModel;
using System.Threading;
using System.IO;



namespace ServerStatusChecks
{
    public partial class Form1 : Form
    {
        private BackgroundWorker bw = new BackgroundWorker();
        public string ScriptName { get; set; }
        static string RunScriptResult;
        public Form1()
        {
            InitializeComponent();
            bw.WorkerReportsProgress = true;
            bw.WorkerSupportsCancellation = true;
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
        }


        public void button1_Click(object sender, EventArgs e)
        {

            if (bw.IsBusy != true)
            {
                bw.RunWorkerAsync();
            }
            // run our script and put the result into our textbox
            // NOTE: make sure to change the path to the correct location of your script

        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (comboBox1.SelectedIndex)
            {
                case 1:
                    ScriptName = @"c:\utils\Script1.ps1";
                    break;
                case 2:
                    ScriptName = @"c:\utils\Script2.ps1";
                    break;
                default:
                    ScriptName = @"c:\utils\Script3.ps1";
                    break;
            }
        }

        private void bw_DoWork(object sender, EventArgs e)
        {
            var loadScript = LoadScript(ScriptName);

            if (string.IsNullOrWhiteSpace(loadScript)) return;

            RunScriptResult = RunScript(loadScript);
        }

        private static string LoadScript(string filename)
        {
            if (!File.Exists(filename)) return "";

            var fileContents = new StringBuilder();

            var lines = File.ReadAllLines(filename);

            foreach (var line in lines)
            {
                fileContents.Append(line + "\n");
            }

            return fileContents.ToString();
        }

        private static string RunScript(string scriptText)
        {
            //should start from this line
            // create Powershell runspace
            Runspace runspace = RunspaceFactory.CreateRunspace();
            runspace.Open();

            // create a pipeline and feed it the script text
            Pipeline pipeline = runspace.CreatePipeline();
            pipeline.Commands.AddScript(scriptText);

            // add an extra command to transform the script output objects into nicely formatted strings
            // remove this line to get the actual objects that the script returns. For example, the script
            // "Get-Process" returns a collection of System.Diagnostics.Process instances.
            pipeline.Commands.Add("Out-String");

            // execute the script
            Collection<PSObject> results = pipeline.Invoke();

            // close the runspace
            pipeline.Dispose();
            runspace.Close();


            StringBuilder stringBuilder = new StringBuilder();
            foreach (PSObject obj in results)
            {
                stringBuilder.AppendLine(obj.ToString());

            }

            // return the results of the script that has
            // now been converted to text
            return stringBuilder.ToString();
        }

        // helper method that takes your script path, loads up the script
        // into a variable, and passes the variable to the RunScript method
        // that will then execute the contents
        private void Form1_Load(object sender, EventArgs e)
        {
            DirectoryInfo dinfo = new DirectoryInfo(@"C:\utils");
            FileInfo[] Files = dinfo.GetFiles("*.ps1");
            foreach (FileInfo file in Files)
            {
                comboBox1.Items.Add(file.Name);
            }
            comboBox1.SelectedIndex = 0;
        }

        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            textBox1.Text = RunScriptResult;
        }
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            Thread.Sleep(1000);
        }

    }

}

1 个答案:

答案 0 :(得分:0)

这就是我要做的事情:

  1. 此属性: private string RunScript(string scriptText)不应该是财产。它应该是一种方法。从中删除getset。并且,您可能需要制作static。此外,我不会使用与顶部属性相同的方法名称。

  2. 添加此逻辑:

    if (comboBox1.SelectedIndex == 0)
    {
        ScriptName = @"c:\utils\Script1.ps1";
    }
    if (comboBox1.SelectedIndex == 1)
    {
        ScriptName = @"c:\utils\Script2.ps1";
    }
    if (comboBox1.SelectedIndex == 2)
    {
        ScriptName = @"c:\utils\Script3.ps1";
    }
    

    comboBox1_SelectedIndexChanged。请注意,我删除了多个变量声明。您应该能够访问位于顶部的那个。

  3. 更改简单StreamReader的{​​{1}}这将返回文件中每一行的数组。如果你真的需要遍历每一行并附加File.ReadAllLines(ScriptName);,你也可以这样做。它使代码更简单。

  4. 所以,我的版本会是这样的:

    \n

    其他一切都应该是相同的