Link to home
Start Free TrialLog in
Avatar of dyarosh
dyarosh

asked on

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?
ASKER CERTIFIED SOLUTION
Avatar of arnold
arnold
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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;
            try
            {
                // If the directory doesn't exist, create it.
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(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");
            Console.ReadLine();

        }
    }
}

Open in new window

Avatar of dyarosh
dyarosh

ASKER

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.