Search code examples
c#environment-variablesstreamwriterpath-combine

Access to path is denied


for some reason when I create my path that will be used for my StreamWriter it creates a folder called test.doc instead of a file called test.doc

Here is my code:

fileLocation = Path.Combine(Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "QuickNote\\");
fileLocation = fileLocation + "test.doc";

Can anyone tell me what I'm doing wrong with my file path?

UPDATE:

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

Sorry for the delay. I posted the question this morning right before I left for work and was in such as hurry that I didn't even think to post the rest of my code. So, here it is. Also I attempted to do a Path.Combine on the 2nd line test.doc but it gives the same problem.


Solution

  • OK, after seeing the complete code:

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

    You are literally calling CreateDirectory with a string ending in "test.doc". It does not matter if a path ends with \ or not, and "<something>\QuickNote\test.doc" is a valid folder path.

    You can replace the code with:

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

         

    No need to create a writer twice.