开发者

XDocument.Save to specific directory?

I'm using this XML classes for the first time and can't find this piece of info.

I'm doing:

xmlDoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));
xmlDoc.Add(n开发者_开发百科ew XElement("Images"));
xmlDoc .Save("C:\\Backup\\images.xml");

But doesn't work. It only works if I use just the filename, like "images.xml", but of course, the file gets saved on the execution path.


By default, you most likely won't be able to save to "C:\Backup" unless you run your program under elevated permissions. You can only save the "user" folders, by default.


Worked for me, must be a permissions issue. Try another directory or make sure c:\Backup exists


I'm posting this because I just came across a similar situation.

I expected that XDocument.Save() would create the path if it didn't exist.

("Expect away!!", I hear you Black Books fans say.)

It seems that it doesn't. Which seems a bit of an omission to me given that other Save methods do. Or they at least have an option to create the path if it doesn't exist.

Anyway I agree that the question is a bit ambiguous but the solution - if it is to do with the path not existing - is to create it first:

if (!Directory.Exists(Path.GetDirectoryName(myFilePath))) Directory.CreateDirectory(Path.GetDirectoryName(_myFilePath));

NOTE: In this example MyFilePath is a complete path including filename and extension. If you have just the path, it would be:

if (!Directory.Exists(myPath))) Directory.CreateDirectory(myPath);

After I added that line, all was well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜