1. 在Unity中调试可行,发布成exe可行,发布成web不行
Application.dataPath 在Unity中调试是在“..Assets”文件夹下, 发布成exe文件是在“..yourName_Data”文件夹下
using UnityEngine;
using System.Collections;
using System.Xml;
public class CallXml
{
//XML文件路径 在Unity中调试
public static string localUrl = Application.dataPath + "/CallExe.xml";
public static XmlDocument ReadAndLoadXml()
{
XmlDocument doc = new XmlDocument();
//Debug.Log("加载xml文档");
doc.Load(localUrl);
return doc;
}
public static string GetPath(string tagName)
{
string _path = "";
XmlDocument xmlDoc = ReadAndLoadXml();
XmlNode provinces = xmlDoc.SelectSingleNode("xml"); //顶层节点
foreach (XmlNode province in provinces)
{
XmlElement _province = (XmlElement)province;
if (tagName == _province.GetAttribute("name"))
{
//根据传入的tagName获取路径
_path = _province.GetAttribute("path");
}
}
return _path;
}
}
调用程序(unity中测试时,发布exe时调用)
Process proc = new Process();
// unity中和发布exe时调用
proc.StartInfo.FileName = CallXml.GetPath("one");
proc.Start();
//可以用下面代码直接调用程序
System.Diagnostics.Process.Start("notepad");
Process.Start(@"C:UsersDELLDesktop123.txt");
//但当报如下错误提示时,就要用上述方式调用程序
error CS0120: An object reference is required to access non-static member `System.Diagnostics.Process.Start()'
2. 发布成web之后调用xml里的文件
using UnityEngine;
using System.Collections;
using System.Xml;
public class CallXmlWeb : MonoBehaviour {
private static WWW _statusFile;
// Use this for initialization
IEnumerator Start ()
{
yield return StartCoroutine(ReadXML());
print(_statusFile.text);
}
private IEnumerator ReadXML()
{
yield return _statusFile = new WWW(Application.dataPath + "/CallExe.xml");
}
public static XmlDocument ReadAndLoadXml()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(_statusFile.text);
return xmlDoc;
}
//根据节点名,读取节点中的值
public static string GetPath(string tagName)
{
string _path = "";
XmlDocument xmlDoc = ReadAndLoadXml();
XmlNode provinces = xmlDoc.SelectSingleNode("xml"); //顶层节点
foreach (XmlNode province in provinces)
{
XmlElement _province = (XmlElement)province;
if (tagName == _province.GetAttribute("name"))
{
//根据传入的tagName获取路径
_path = _province.GetAttribute("path");
}
}
return _path;
}
}
调用程序(发布web时调用)
注意1: 此时用下面代码调用不会有结果,因为web的安全机制,不能随便调用本地程序。 传入路径/xx/xx.exe等也不行,网上有其它的解决方法。
proc.StartInfo.FileName = CallXmlWeb.GetPath("notepad");
但可以用GetPath("notepad");读取到XML文件里面的内容
注意2:从其他函数调用此函数时,读取不到XML里的内容,在一个函数内部测试就可以,暂不知道原因。
3. XML文件CallExe.xml
<?xml version="1.0" encoding="utf-8"?> <xml> <tag name ="notepad" path ="notepad"> </tag> <tag name ="qq" path ="C:Program Files (x86)TencentQQQQProtectBinQQProtect.exe"> </tag> <tag name ="jisuanqi" path ="calc"> </tag> </xml>