路径C#中的非法字符到Ironpython

时间:2014-12-20 15:35:02

标签: c# python ironpython filepath

我正在尝试将包含文件路径的变量从我的C#应用​​程序传递到我的C#应用​​程序中的temp.xml文件,但我一直得到Illegal Characters in Path异常。我觉得我几乎完成了Stackoverflow上提到的所有内容,以修复C#端和Python端的非法字符/路径,但似乎没有任何工作。我如何克服这个障碍??

以下是我用来打开/替换错误字符并将temp.xml写入C:\Temp\目录的C#代码:

StreamReader sr1 = new StreamReader(filePath);
string tempFile = @"C:\Temp\temp.xml";

File.Copy(filePath, tempFile, true);
StreamWriter sw = new StreamWriter(tempFile);
sw.AutoFlush = true;

string xml = sr1.ReadToEnd();
string regExp = @"</(\w+)>";
MatchCollection mc = Regex.Matches(xml, regExp);
foreach (Match m in mc)
{
    string val = m.Groups[1].Value;
    string regExp2 = "<" + val + "( |>)";
    Match m2 = Regex.Match(xml, regExp2);
    if (m2.Success)
    {
         char[] chars = xml.ToCharArray();
         chars[m2.Index] = '~';
         xml = new string(chars);
         xml = Regex.Replace(xml, @"</" + val + ">", "~/" + val + ">");
    }

         xml = Regex.Replace(xml, @"<\?", @"~?"); // declarations
         xml = Regex.Replace(xml, @"<!", @"~!");   // comments
 }

   string regExp3 = @"<\w+\s?/>";
   Match m3 = Regex.Match(xml, regExp3);
   if (m3.Success)
   {
       char[] chars = xml.ToCharArray();
       chars[m3.Index] = '~';
       xml = new string(chars);
   }

     xml = Regex.Replace(xml, "&gt;|-&gt;", ">");
     xml = Regex.Replace(xml, "&lt;", "<");
     xml = Regex.Replace(xml, "~", "<");
     xml = Regex.Replace(xml, "&", "&");
     xml = Regex.Replace(xml, "“|”", "\"");
     xml = Regex.Replace(xml, "’", "'");
     xml = Regex.Replace(xml, "‘", "\"");
     xml = Regex.Replace(xml, "–", "-");
     sw.WriteLine(xml);
     sw.Close();

     ScriptEngine engine = Python.CreateEngine();
     ScriptScope scope = engine.CreateScope();
     var paths = engine.GetSearchPaths();
     paths.Add(@"C:\Program Files (x86)\IronPython 2.7\Lib");
     engine.SetSearchPaths(paths);

     var parameters = new Dictionary<string, object>()
     {
       {"scapFilePath", tempFile}, {"scapProfile", profile}
     };
     scope = engine.CreateScope(parameters);

     //EXCEPTION IS THROWN HERE
     try
     {
         dynamic result = engine.ExecuteFile("xccdf-xml2tsv.py", scope);
     }
     catch (Exception e)
     {
          Messagebox.Show(e.toString());
     }

     Console.WriteLine("Press any key to exit");
     Console.ReadKey();
}

以下是我在python脚本中处理上面定义的scope变量的代码:

import csv
import sys
import os
import traceback
reload(sys)
sys.setdefaultencoding('utf-8')
import xml.etree.ElementTree as ET
xmlns = "http://checklists.nist.gov/xccdf/1.1"

scapFile = os.path.normpath(scapFilePath)

try:
    xml = ET.parse(scapFile)
except Exception,e:
    traceback.print_exc()
    sys.exit(-1)

以下是我在异常时的scope变量:

enter image description here

以下是例外:

enter image description here

感谢任何帮助;我已经被困在这两天了!!

1 个答案:

答案 0 :(得分:2)

在包含变量的屏幕截图中

["outFileName"]

显示为包含

"c:\\Temp\tmp.csv"

所以代替第二个反斜杠(在tmp.csv之前)它包含一个tab chararcter