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?