出于某种原因,当我创建将用于我的 StreamWriter 的路径时,它会创建一个名为 test.doc 的文件夹,而不是一个名为 test.doc 的文件
这是我的代码:
fileLocation = Path.Combine(Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "QuickNote\\");
fileLocation = fileLocation + "test.doc";
谁能告诉我我的文件路径有什么问题?
更新:
class WordDocExport
{
string fileLocation;
public void exportDoc(StringBuilder sb)
{
fileLocation = Path.Combine(Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "QuickNote\\");
fileLocation = fileLocation + "test.doc";
if (!Directory.Exists(fileLocation))
{
Directory.CreateDirectory(fileLocation);
using (StreamWriter sw = new StreamWriter(fileLocation, true))
{
sw.Write(sb.ToString());
}
}
else
{
using (StreamWriter sw = new StreamWriter(fileLocation, true))
{
sw.Write(sb.ToString());
}
}
}
}
抱歉耽搁了。今天早上我在去上类之前发布了这个问题,当时我太着急了,以至于我什至没有想过发布我的代码的其余部分。所以,就在这里。我还尝试在第二行 test.doc 上执行 Path.Combine,但它给出了同样的问题。
最佳答案
OK,看到完整代码后:
fileLocation = fileLocation + "test.doc";
if (!Directory.Exists(fileLocation))
{
Directory.CreateDirectory(fileLocation); // this is the _complete_ path
using (StreamWriter sw = new StreamWriter(fileLocation, true))
{
sw.Write(sb.ToString());
}
}
您实际上是使用以“test.doc”结尾的字符串调用 CreateDirectory。路径是否以 \
结尾并不重要与否,和"<something>\QuickNote\test.doc"
是一个有效的文件夹路径。
您可以将代码替换为:
string rootFolderPath = Environment.GetFolderPath(
System.Environment.SpecialFolder.MyDocuments);
string folderPath = Path.Combine(rootFolderPath, "QuickNote");
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
fileLocation = Path.Combine(folderPath, "test.doc");
using (StreamWriter sw = new StreamWriter(fileLocation, true))
{
sw.Write(sb.ToString());
}
无需创建 writer 两次。
关于c# - 访问路径被拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12054506/