1

I have a .js file that performs a fairly simple task of building an array strings. Without going into too much detail, I have found Javascript the best language to perform this specific task.

What I want now is to access that array in my C# application. Javascript cannot access the filesystem, so writing the array to a file before reading it with C# is out of the question.

Is there an easy way to do this? Can these two languages interact at all?

2
  • 1
    JSC was always part of .Net... So if you are fine to compile it first you can get normal .Net executable out of your JavaScript... Also unclear why you can't access file system with presumably local JavaScript... Commented Apr 10, 2014 at 20:19
  • You tagged this question with Jquery, is this a web application? Commented Apr 10, 2014 at 20:20

3 Answers 3

1

Give a check to a JavaScript parser called Jurassic:

For example, taken from their docs:

var engine = new Jurassic.ScriptEngine();
Console.WriteLine(engine.Evaluate("5 * 10 + 2"));
Sign up to request clarification or add additional context in comments.

1 Comment

@user3478799 No problem! You can still mark it as the right answer if you found it useful!
0

Assuming local JavaScript on Windows.

You can definitely access files with local JavaScript as with any other scripting language.

Here is sample to create file form Working with files MSDN article:

function CreateFile()
{
   var fso = new ActiveXObject("Scripting.FileSystemObject");
   var tf = fso.CreateTextFile("c:\\testfile.txt", true);
   tf.WriteLine("Testing 1, 2, 3.") ;
   tf.Close();
}

You can also compile some JavaScript with .Net JSC compiler to get executable (or probably even .Net assembly) if you need to.

Comments

0

Why not? Assuming that this is a web form C# application you can access Javascript function from C# code using ScriptManager class which is part of System.Web.UI

 protected void Page_Load(object sender, EventArgs e)
 {
        ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "GetData", "Javascript:getArrayValues();", true);
 }

In the HTML markup define a tag like

<asp:HiddenField ID ="hfArrayValues" runat ="server" Value ="" />

In getArrayValues() JS function you can store the array value into a hidden variable and then access this value from code behind

 function getArrayValues() {
        var arr = ["value 1", "value 2", "value 3"];
        var hfvalue = document.getElementById('hfArrayValues').value = arr;
 }

and your C# method where you can access the array values

 protected void Button1_Click(object sender, EventArgs e)
 {
        Response.Write(hfArrayValues.Value);
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.