c#执行javascript函数

先去http://www.microsoft.com/zh-cn/download/details.aspx?id=1154微软官网下载Windows Script Control,安装后添加MSScriptControl引用

代码实现:

         private void button_Click(object sender, EventArgs e)
        {
            //脚本位置
            string path = "E:\\TestDescrypt\\TestDescrypt\\JScript1.js";

            string str2 = File.ReadAllText(path);

            //hex_md5('{0}')  hex_md5为函数名  ('{0},{1}')为参数

            string fun = string.Format(@"hex_md5('{0}')", this.textBox1.Text);
            string result = ExecuteScript(fun, str2);
            this.label1.Text = result;
            Console.WriteLine(result);
        }


        private string ExecuteScript(string sExpression, string sCode)
        {
            MSScriptControl.ScriptControl scriptControl = new MSScriptControl.ScriptControl();
            scriptControl.UseSafeSubset = true;
            scriptControl.Language = "JScript";
            scriptControl.AddCode(sCode);
            try
            {
                string str = scriptControl.Eval(sExpression).ToString();
                return str;
            }
            catch (Exception ex)
            {
                string str = ex.Message;
            }
            return null;
        }

你可能感兴趣的:(c#学习)