将文件保存到 Path.Combine 目录
Saving file into Path.Combine directory
有人可以告诉我如何将文件保存到 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 = "Whosebug";
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);
}
它在名为 Whosebug\Test
的桌面文件夹中创建一个名为 xmltest.xml
的文件。
这可行,但我建议为文件夹和文件路径创建单独的变量。这将使代码更清晰,因为每个变量只有一个目的,并且会减少此类错误的可能性。例如:
void Main()
{
string mainFolder = "Whosebug";
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);
}
好人,
非常感谢您的反馈和快速的转变。正如您所提到的,在实际创建 if 之前,我正在更改 wholesalePath
的操作。
void Main()
{
string mainFolder = "Whosebug";
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)
,然后是 wholesalePath = Path.Combine(wholesalePath, fileName)
,所以一切都很顺利。再次感谢您的帮助。
非常感谢。