我有以下代码:
fileinfo = new FileInfo(filePathAndName);
if (!fileinfo.Exists)
{
using (xmlWriter = new XmlTextWriter(filePathAndName, System.Text.Encoding.UTF8))
{
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("root");
xmlWriter.WriteStartElement("objects");
xmlWriter.WriteEndElement();
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
xmlWriter.Close();
}
}
filePathAndName将为C:/MyApp%205/Produkter/MyApp%20Utveckling/Host/Orbit.Host.Dev/bin/ExceptionLog.xml.
文件夹确实存在,但文件不存在。在这种情况下,XmlTextWriter应该创建文件,但它会抛出Could not find part of the path
。
这可能是我在这里忘记的非常明显的事情,请帮忙。
编辑:路径的实际情况如下:
C:\MyApp 5\Produkter\MyApp Utveckling\Host\Orbit.Host.Dev\Bin
这就是生成代码中使用的URL的方式:
(new System.Uri(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase) + "\\ExceptionLog.xml")).AbsolutePath
答案 0 :(得分:3)
我已尝试过代码ArgumentException
由XmlTextWriter
构造函数抛出此消息:
不支持URI格式。
请考虑以下代码:
// Get the path to assembly directory.
// There is a lot of alternatives: http://stackoverflow.com/questions/52797/
var assemblyPath = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath;
var directoryPath = Path.GetDirectoryName(assemblyPath);
// Path to XML-file.
var filePath = Path.Combine(directoryPath, "ExceptionLog.xml");
using (var xmlTextWriter = new XmlTextWriter(filePath, Encoding.UTF8))
{
...
}
答案 1 :(得分:1)
试试这个 - 在filePathAndName之前添加@
string filePathAndName = @"C:\MyApp 5\Produkter\MyApp Utveckling\Host\Orbit.Host.Dev\Bin\text.xml";
FileInfo fileinfo = new FileInfo(filePathAndName);
if (!fileinfo.Exists)
{
using (XmlTextWriter xmlWriter = new XmlTextWriter(filePathAndName, System.Text.Encoding.UTF8))
{
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("root");
xmlWriter.WriteStartElement("objects");
xmlWriter.WriteEndElement();
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
xmlWriter.Close();
}
}
答案 2 :(得分:1)
如果要与网络上的路径(也称为UNC路径)进行交互,则必须使用Server.MapPath将UNC路径或虚拟路径转换为.NET可以理解的物理路径。因此,只要您打开文件,创建,更新和删除文件,打开目录并删除网络路径上的目录,就可以使用Server.MapPath
。
示例:
System.IO.Directory.CreateDirectory(Server.MapPath("\\server\path"));
答案 3 :(得分:0)
不应使用Uri.AbsolutePath
,而应使用Path.Combine()
var filepath = @"C:\MyApp 5\Produkter\MyApp Utveckling\Host\Orbit.Host.Dev\Bin"
var filename = Path.Combine(filepath, "ExceptionLog.xml");
var fileInfo = new FileInfo(filename);
if(!fileInfo.Exists)
{
//ToDo: call xml writer...
}
答案 4 :(得分:0)
使用Assembly.Location和Path.Combine形成fileNameAndPath变量:
var folder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var filePathAndName = Path.Combine(folder, "ExceptionLog.xml");