2

有人可以建议我如何将文件保存到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”中的另一个目录。

我将不胜感激任何建议。

4

2 回答 2

2

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

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);
}

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

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

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);
}
于 2018-05-12T18:03:34.197 回答
0

好地方,伙计们,

非常感谢您的反馈和快速上交。正如您所提到的,我正在更改wholesalePath实际创建之前的操作。

void Main()
{
    string mainFolder = "StackOverflow";
    string wholesaleFolder = "Test";
    string wholesalePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), mainFolder, wholesaleFolder);

    wholesalePath = Path.Combine(wholesalePath, fileName);

    Directory.CreateDirectory(wholesalePath);
    string fileName = "xmltest.xml";
    XmlDocument doc = new XmlDocument();
    string oneLine = "<root></root>";
    doc.Load(new StringReader(oneLine));
    doc.Save(wholesalePath);
}

现在,由于我已将执行顺序更改为Directory.CreateDirectory(wholesalePath)as first,然后wholesalePath = Path.Combine(wholesalePath, fileName)一切都像魅力一样工作。再次感谢您的支持。

非常感激。

于 2018-05-13T07:18:43.000 回答