Click here to Skip to main content
15,910,212 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
I am having trouble formatting a datetime to use as part of a file name. I am needing it to look like this: yyyy/dd/mm hh:mm:ss. I keep getting the error that the file path could not be found. I searched the forum and found an example that looked like mine but it did not help when I implemented it. Thank you for your help.

C#
DateTime date = DateTime.Now;
                    string dateNow = date.ToString();
                    string saveTime = String.Format("s = {0:s}", dateNow);
                    saveTime.Replace('/', '-').Replace(':', '-');

                    try
                    {
                        OleDbDataReader dr1 = cmd.ExecuteReader();
                        StreamWriter sw = new StreamWriter(@"C:\travelersTEST\travelersExport" + saveTime + ".csv");
                        if (dr1.HasRows)
                        {
                            dt.Load(dr1);
                            dt.AcceptChanges();
                        }
                        // Now write all the rows.

                        sw.Write("Policy Number, Effective Date, Transaction Premium, Comm Rate, Comm Due");
                        sw.Write(sw.NewLine);
                        
                            foreach (DataRow dr in dt.Rows)
                            {
                                if (dr[0].ToString() != "")
                                {
                                    sw.Write(dr[0].ToString() + ",");
                                    sw.Write(dr[1].ToString() + ",");
                                    sw.Write(dr[2].ToString() + ",");
                                    sw.Write(dr[3].ToString() + ",");
                                    sw.Write(dr[4].ToString());
                                    sw.Write(sw.NewLine);
                                }
                                
                            }
                        sw.Close();
                    }
<pre lang="cs">catch (OleDbException caught)
                    {
                        Response.Write(caught.Message);
                    }
                    finally
                    {
                        conn.Close();
                    }

                    string fileName = ("travelersExport" + saveTime + ".csv");
                    string filePath = (@"C:\travelersTEST\travelersExport" + saveTime + ".csv");

                    Response.Clear();
                    Response.AppendHeader("content-disposition",
                    "attachment; filename=" + fileName);
                    Response.ContentType = "application/octet-stream";
                    Response.WriteFile(filePath);
                    Response.Flush();
                    Response.End();
                }
            }
            else
            {
                Response.Write("This file does not exist.");
            }
        }
Posted
Updated 30-May-12 10:08am
v3

You can't put '/' or '\' characters in file names as you have found - so use the '-' instead.
You don't have to play with it at all - DateTime.ToSting has an overload that takes a format specification, which will allow you to generate the name directly:
C#
string dateString = DateTime.Now.ToString("yyyy-MM-dd");


Have a look here: Formatting a DateTime for display - format string description[^]
 
Share this answer
 
Comments
Maciej Los 30-May-12 16:09pm    
Good answer, my 5!
Richard C Bishop 30-May-12 17:33pm    
So much easier, thank you!
OriginalGriff 31-May-12 3:34am    
You're welcome!
Espen Harlinn 31-May-12 15:20pm    
5'ed!
Please see:
http://msdn.microsoft.com/en-us/library/system.datetime.aspx[^].

Pay attention for different ToString methods allowing to use CultureInfo (see the parameter IFormatProvider which is implemented by CultureInfo) or detailed format features, standard or custom:
http://msdn.microsoft.com/en-us/library/az4se3k1.aspx[^],
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx[^].

You are just doing wring things manipulating your string. In particular, your repeated string concatenation is bad. This is not readable and has poor performance, because strings are immutable (do I have to explain why?). The type System.Text.StringBuilder and the method string.Format are free from this problem. Using (especially repeated using of immediate constants) like "," is very bad for maintenance. You should always use explicit constant (one definition of all uses of it) or resources.

—SA
 
Share this answer
 
Comments
Maciej Los 30-May-12 16:09pm    
Complete answer, my 5!
Sergey Alexandrovich Kryukov 30-May-12 17:01pm    
Thank you, Maciej.
--SA
Richard C Bishop 30-May-12 17:34pm    
Thank you, I will look into that info.
Sergey Alexandrovich Kryukov 30-May-12 18:30pm    
You are welcome
And please consider accepting this answer formally (green button); you can accept more than one -- thanks.
--SA
El_Codero 30-May-12 19:31pm    
Good points, my 5.Regards

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900