c# - 将文件保存到 Path.Combine 目录中

标签 c# xmldocument path-combine

有人可以建议我如何将文件保存到 Path.Combine 目录中吗? 请在下面找到我的一些代码。

创建目录:

string wholesalePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), mainFolder, wholesaleFolder);
Directory.CreateDirectory(wholesalePath);

我还指定了应该使用的文件名。

 string fileName = "xmltest.xml";

然后我重新创建了一个“wholesalePath”来包含文件名:

wholesalePath = Path.Combine(wholesalePath, fileName);

执行几行简单的代码:

        XmlDocument doc = new XmlDocument();
        string oneLine = "some text";
        doc.Load(new StringReader(oneLine));
        doc.Save(fileName);
        Console.WriteLine(doc);

我遇到的问题是,当我使用doc.Save(fileName)时,我在 VisualStudio 项目目录中获取文件,该目录是错误的目录。

但是,当我使用doc.Save(wholesalePath)时,应该创建的文件“xmltest.xml”实际上被创建为“wholesalePath”中的另一个目录。

如果有任何建议,我将不胜感激。

最佳答案

正如评论中所说,在附加fileName之前,您需要使用wholesalePath创建目录。您需要在附加 fileName 后使用 wholesalePath 来保存文件。我测试了以下代码,它按预期工作:

void Main()
{
    string mainFolder = "StackOverflow";
    string wholesaleFolder = "Test";
    string wholesalePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), mainFolder, wholesaleFolder);
    Directory.CreateDirectory(wholesalePath);
    string fileName = "xmltest.xml";
    wholesalePath = Path.Combine(wholesalePath, fileName);
    XmlDocument doc = new XmlDocument();
    string oneLine = "<root></root>";
    doc.Load(new StringReader(oneLine));
    doc.Save(wholesalePath);
}

它会在名为 StackOverflow\Test 的桌面文件夹中创建一个名为 xmltest.xml 的文件。

这可行,但我建议为文件夹和文件路径创建单独的变量。这将使代码更加清晰,因为每个变量只有一个用途,并且会降低出现此类错误的可能性。例如:

void Main()
{
    string mainFolder = "StackOverflow";
    string wholesaleFolder = "Test";
    string fileName = "xmltest.xml";
    string destinationFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), mainFolder, wholesaleFolder);
    string destinationFilePath = Path.Combine(destinationFolder, fileName);

    Directory.CreateDirectory(destinationFolder);
    XmlDocument doc = new XmlDocument();
    string oneLine = "<root></root>";
    doc.Load(new StringReader(oneLine));
    doc.Save(destinationFilePath);
}

关于c# - 将文件保存到 Path.Combine 目录中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50308867/

相关文章:

Java算法到 "multiply"两个列表列表((A),(B))*((C,C),(D,D))==((A,C,C),(A,D,D), (B,C,C),(B,D,D))

c# - 在哪里存储将在我的应用程序中使用的常量对象

c# - 如何使用 GDI 为多行文本的某些部分添加下划线?

C#在搜索图像中的像素时for循环性能低下

.net - XmlDocument缓存内存使用

asp.net - 何时在XmlDocument或XmlTextReader上使用XPath?

c# - 如何在 C# 中使用 XmlDocument 停止空 XML 元素自关闭?

c# - 处理后流式传输 IConnectableObservable

c# - 访问路径被拒绝