Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could not find a part of the path 'C:\

Tags:

c#

directory

Im getting this error. Even though i already created a folder "CMSExportedData" Could not find a part of the path 'C:\CMSExportedData\Sales-20\07\2012.txt'.

Kindly help please

using (FileStream fs = new FileStream("C:\\CMSExportedData\\Sales-" + DateTime.Now.ToString("dd/MM/yyyy") + ".txt", FileMode.Create))
{
    using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
    {
        //use stream
    }
}
like image 221
Newbie Avatar asked Dec 06 '22 13:12

Newbie


2 Answers

You're formatting the date as part of the filename in such a way that the date separators are slashes, which get converted to backslashes (path separators) by the path logic:

'C:\CMSExportedData\Sales-20\07\2012.txt'.

There's no Sales-20 folder, and no 07 folder.

Solution: don't use path separator characters in your file names :). This solution also formats the date as year-month-day because that makes the file names sort in chronological order:

"C:\\CMSExportedData\\Sales-" + DateTime.Now.ToString("yyyyMMdd") + ".txt"
like image 68
phoog Avatar answered Dec 22 '22 12:12

phoog


A filename cannot contain any of the following characters:

\ / : * ? " < > |

apparently your date formatting uses '/' that is not allowed. A suggestion can be to use '-' as a separator so your file will be:

C:\CMSExportedData\Sales-20-07-2012.txt

Just for completeness, non alphanumeric charachters accebtable are:

 ^   Accent circumflex (caret)
   &   Ampersand
   '   Apostrophe (single quotation mark)
   @   At sign
   {   Brace left
   }   Brace right
   [   Bracket opening
   ]   Bracket closing
   ,   Comma
   $   Dollar sign
   =   Equal sign
   !   Exclamation point
   -   Hyphen
   #   Number sign
   (   Parenthesis opening
   )   Parenthesis closing
   %   Percent
   .   Period
   +   Plus
   ~   Tilde
   _   Underscore
like image 43
Felice Pollano Avatar answered Dec 22 '22 11:12

Felice Pollano