我正在尝试将XDocument
对象保存到磁盘,作为.xml文件。该对象似乎在调试器中很好地形成,我只是在保存实际文件时遇到问题。这就是我正在做的事情:
//ofx is an `XElement` containing many sub-elements of `XElement` type
XDocument document = new XDocument(ofx);
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.Indent = true;
//destinationPath is a string containing a path, like this
// e.g : "C:\\Users\\Myself\\Desktop"
using (var stream = File.Create(destionationPath + @"export.xml"))
{
List<byte[]> header = new List<byte[]>();
byte[] newline = Encoding.ASCII.GetBytes(Environment.NewLine);
List<string> headers = new List<string>();
headers.Add("foo");
// Just adding some headers here on the top of the file.
// I'm pretty sure this is irrelevant for my problem
foreach (string item in headers)
{
header.Add(Encoding.ASCII.GetBytes(item));
header.Add(newline);
}
header.Add(newline);
byte[] bytes = header.SelectMany(a => a).ToArray();
stream.Write(bytes, 0, bytes.Length);
using (var writer = XmlWriter.Create(stream, settings))
{
document.Save(writer);
}
}
每当我调用它时,目标目录中都没有文件。
注意:目录格式正确,文件名也是如此。这在代码中得到验证。
答案 0 :(得分:2)
可能你正在严重创造这条道路。评论后你有
string destionationPath = "C:\\Users\\Myself\\Desktop";
destionationPath + @"export.xml" // evaluates to: "C:\\Users\\Myself\\Desktopexport.xml"
目录和文件名之间缺少"\\"
。
以下代码适用于我。
namespace TestApp
{
class Program
{
static void Main(string[] args)
{
Tmp();
}
public static void Tmp()
{
//ofx is an `XElement` containing many sub-elements of `XElement` type
XDocument document = new XDocument(new XElement("myName", "myContent"));
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.Indent = true;
//destinationPath is a string containing a path, like this
// e.g : "C:\\Users\\Myself\\Desktop"
string destionationPath = "D:\\Temp\\xml_test\\";
using (var stream = File.Create(destionationPath + @"export.xml"))
{
List<byte[]> header = new List<byte[]>();
byte[] newline = Encoding.ASCII.GetBytes(Environment.NewLine);
List<string> headers = new List<string>();
headers.Add("foo");
// Just adding some headers here on the top of the file.
// I'm pretty sure this is irrelevant for my problem
foreach (string item in headers)
{
header.Add(Encoding.ASCII.GetBytes(item));
header.Add(newline);
}
header.Add(newline);
byte[] bytes = header.SelectMany(a => a).ToArray();
stream.Write(bytes, 0, bytes.Length);
using (var writer = XmlWriter.Create(stream, settings))
{
document.Save(writer);
}
}
}
}
}
为了避免这种情况,永远不会通过yoursef创建创建路径。请改用Path
类:
Path.Combine(destionationPath, @"export.xml")