有人可以建议我如何将文件保存到 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/