4

我有以下代码:

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
4

5 回答 5

3

我已经尝试过代码,ArgumentExceptionXmlTextWriter构造函数抛出此消息:

不支持 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))
{
    ...
}
于 2013-01-29T14:14:56.467 回答
1

如果您正在与网络上的路径(也称为 UNC 路径)进行交互,则必须使用 Server.MapPath 将 UNC 路径或虚拟路径转换为 ​​.NET 可以理解的物理路径。因此,每当您在网络路径上打开文件、创建、更新和删除文件、打开目录和删除目录时,请使用Server.MapPath.

例子:

System.IO.Directory.CreateDirectory(Server.MapPath("\\server\path"));
于 2014-05-02T18:46:08.343 回答
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();
    }
}
于 2013-01-29T14:13:39.407 回答
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...
}
于 2013-01-29T14:16:23.623 回答
0

使用 Assembly.Location 和 Path.Combine 形成您的 fileNameAndPath 变量:

var folder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var filePathAndName = Path.Combine(folder, "ExceptionLog.xml");
于 2013-01-29T14:17:25.297 回答