【问题标题】:Getting the string from IronPython source code with C#使用 C# 从 IronPython 源代码中获取字符串
【发布时间】:2010-10-11 17:34:29
【问题描述】:

IronPython In Action的书有如下代码,将python脚本读入字符串。 (第 15.2 章)

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

它将 BasicEmbedding.source_code.py 读取为一个字符串。我刚刚复制到我的代码,但出现以下错误。 (只需从示例代码运行即可)

未处理的异常:System.ArgumentNullException:参数不能为空。 参数名称:流 在 System.IO.StreamReader.Initialize(System.IO.Stream 流,System.Text.Encoding 编码,布尔检测EncodingFromByteOrderMarks,Int32 bufferSize)[0x00000] 在:0 在 System.IO.StreamReader..ctor (System.IO.Stream 流,System.Text.Encoding 编码,布尔检测EncodingFromByteOrderMarks,Int32 bufferSize)[0x00000] 在:0 在 System.IO.StreamReader..ctor (System.IO.Stream 流) [0x00000] in :0 在 (wrapper remoting-invoke-with-check) System.IO.StreamReader:.ctor (System.IO.Stream) 在 BasicEmbedding.Program.GetSourceCode (System.String pythonFileName) [0x00000] in :0 在 BasicEmbedding.Program.Main () [0x00000] in :0

我想我可以实现如下相同的功能,它工作正常。

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();
}

问题

  • 对于原始代码,“assembly.GetManifestResourceStream()”函数是什么,为什么会出现错误?
  • 我的新代码和旧代码的执行结果一样吗?

【问题讨论】:

    标签: c# .net ironpython


    【解决方案1】:
    • 对于原始代码,“assembly.GetManifestResourceStream()”函数是什么,为什么会出现错误?:它寻找编译到您的应用程序中的embedded resource使用给定的名称。很可能,您没有添加具有该名称的资源。

    • 我的新代码在执行结果方面与旧代码相同吗?:不。您从磁盘中读取具有给定名称的文件,与程序集位于同一目录中.原始从程序集读取资源。

    【讨论】:

      猜你喜欢
      • 2010-11-02
      • 1970-01-01
      • 1970-01-01
      • 2020-02-16
      • 1970-01-01
      • 1970-01-01
      • 2010-11-20
      • 2012-05-28
      • 1970-01-01
      相关资源
      最近更新 更多