Need to create a file in a folder in My Documents using c#

I am developing a Windows Application and I need to create a file in the following folder:  My Documents\HWLocal77\Exports

Here is the code that I am using:
string CensusFileName = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\HWLocal77\Exports\Census_" + curDate.Month.ToString() + curDate.Year.ToString() + ".txt"

Open in new window

When my code tries to open the file I get the following error message:
Could not find a part of the path 'C:\Users\username\Documents\HWLocal77\Exports\Census_52015.txt'.

In tracing the error, C:\Users\username exists.  Documents folder does not exist but My Documents folder does.  

Can anyone tell me what I need to change so I can access the My Documents\HWLocal77\Exports folder regardless of which machine the application is installed on?
Who is Participating?
You first must make sure the oath is there creating the directories if missing.
The other part you have to check which system you are on decide whether my documents or documents is the correct location as well as taking into account the possibility that folder redirection might be employed.

You need to get registry info for shell folders to be certain where it is
HKCU\software\microsoft\windows\currentversion\explorer\shell folders\ I think that is the correct path. Where you can see where desktop, my documents, etc. are.
David Johnson, CD, MVPOwnerCommented:
using System;
using System.IO;

namespace Q_28673387
    class Program
        static void Main(string[] args)
            string documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            string path = documents + @"\HWLocal77\Exports\";
            DateTime curDate = DateTime.Now;
                // If the directory doesn't exist, create it.
                if (!Directory.Exists(path))
            catch (IOException e)
                if (e.Source != null) Console.WriteLine("OOPS, We have a problem {0}", e.Source);
            string filename = "Census_" + curDate.Month.ToString() + curDate.Year.ToString() + ".txt";
            Console.WriteLine("OK so far, hit enter to exit");


Open in new window

dyaroshAuthor Commented:
Using your suggestion I checked to see if the path exists and discovered one of my folders had a space in it that was missing in my string.  The Documents folder mapped to the My Documents folder.  Your suggestion helped lead me to the answer.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.