c# - 访问路径被拒绝

标签 c# environment-variables streamwriter path-combine

出于某种原因,当我创建将用于我的 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/

相关文章:

c# - 无法读取流 (StreamReader .net),使用 Angular (1.5) $http.post 和 json 作为数据从 Internet Explorer 10 发送

c# - Windows Phone 7 DownloadStringCompleted 的 URL 是什么?或者参数?

json - 使用 jq 将 x=y 对转换为键/值对

docker - docker-compose.yml不会读取主机名的环境变量

c# - 将许多变量写入文本文件

Android客户端使用Socket发送大文件,服务器收到的文件不完整

C#哈希密码创建盐问题

c# - 如何在特定时间触发.NET Core 3.1 Hosted Service?

c - VS2012 上 getenv/putenv 的内存损坏

c# - 将对象列表写入文本文件