1

The book of IronPython In Action has the following code to read python script into a string. (Chapter 15.2)

static string GetSourceCode(string pythonFileName)
{
    Assembly assembly = Assembly.GetExecutingAssembly();
    Stream stream = assembly.GetManifestResourceStream(pythonFileName);
    StreamReader textStreamReader = new StreamReader(stream);
    return textStreamReader.ReadToEnd();
}

It reads BasicEmbedding.source_code.py to a string. I just copied to my code, but I got the following error. (Just running from example code is OK)

Unhandled Exception: System.ArgumentNullException: Argument cannot be null.
Parameter name: stream
  at System.IO.StreamReader.Initialize (System.IO.Stream stream, System.Text.Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize) [0x00000] in :0 
  at System.IO.StreamReader..ctor (System.IO.Stream stream, System.Text.Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize) [0x00000] in :0 
  at System.IO.StreamReader..ctor (System.IO.Stream stream) [0x00000] in :0 
  at (wrapper remoting-invoke-with-check) System.IO.StreamReader:.ctor (System.IO.Stream)
  at BasicEmbedding.Program.GetSourceCode (System.String pythonFileName) [0x00000] in :0 
  at BasicEmbedding.Program.Main () [0x00000] in :0 

I think I can implement the same function as follows, which works OK.

static string GetSourceCode(string pythonFileName)
{
    Assembly assembly = Assembly.GetExecutingAssembly();
    string path = assembly.Location;
    string rootDir = Directory.GetParent(path).FullName;
    string pythonScript = Path.Combine(rootDir, pythonFileName);

    StreamReader textStreamReader = File.OpenText(pythonScript);

    return textStreamReader.ReadToEnd();
}

Question

  • For the original code, what's for the "assembly.GetManifestResourceStream()" function, and why do I get the error?
  • Is my new code the same as the old code in terms of execution result?

1 Answer 1

3
  • For the original code, what's for the "assembly.GetManifestResourceStream()" function, and why do I get the error? : It looks for an embedded resource compiled into your application with the given name. Most likely, you are not adding a resource with that name.

  • Is my new code the same as the old code in terms of execution result? : No. Your reads a file from disk with the given name, in the same directory as the assembly. The original reads a resource from within the assembly.

Sign up to request clarification or add additional context in comments.

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.