views:

1030

answers:

5

Hey all.

I am trying to get the following: [today's date]___[textfilename].txt from the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication29
{
    class Program
    {
        static void Main(string[] args)
        {
            WriteToFile();

        }

        static void WriteToFile()
        {

            StreamWriter sw;
            sw = File.CreateText("c:\\testtext.txt");
            sw.WriteLine("this is just a test");
            sw.Close();
            Console.WriteLine("File created successfully");



        }
    }
}

I tried putting in DateTime.Now.ToString() but i cannot combine the strings.

Can anybody help me? I want the date in FRONT of the title of the new text file I am creating.

+11  A: 

You'd want to do a custom string format on DateTime.Now. You can use String.Format() to combine the results of that with your base filename.

To append on the path to the filename, use Path.Combine().

Finally, use a using() block to properly close & dispose your StreamWriter when you are finished with it...

string myFileName = String.Format("{0}__{1}", DateTime.Now.ToString("yyyyMMddhhnnss"), "MyFileName");
strign myFullPath = Path.Combine("C:\\Documents and Settings\\bob.jones\\Desktop", myFileName)
using (StreamWriter sw = File.CreateText(myFullPath))
{
    sw.WriteLine("this is just a test");
}

Console.WriteLine("File created successfully");

Edit: fixed sample to account for path of "C:\Documents and Settings\bob.jones\Desktop"

Scott Ivey
string myFileName = String.Format("{0}__{1}", DateTime.Now.ToString("yyyyMMddhhnnss"), "MyFileName"); StreamWriter sw = File.CreateText(myFileName);
CSharpAtl
You keep saying "did not work". Nobody can help you figure it out unless you tell us HOW it didn't work. Saying "this did not work" without more information is a waste of your time and ours.
Ken White
this works for the most part...but how can i specify the exact path in where this .txt should be created in? for example, i want this .txt file to be created on C:\\Documents and Settings\\bob.jones\\Desktop how would i specify this?
+1 for stripping out non-digit, possibly illegal in file names characters via formatting.
JeffH
A: 
sw = File.CreateText(@"C:\" + DateTime.Now.ToString().Replace('/', '-',).Replace(':','') + "_testtext.txt");
MasterMax1313
Sorry, but String Replacing on a Date is going to get you into Hell as soon as you run your app in a different Culture, for example one that does not use / to separate Dates. Either Specify the Culture explicitly, or use one of the many Methods/Fields of DateTime.Now
Michael Stum
He never specified that it needed to be culture agnostic
MasterMax1313
You'll definitely want to learn about DateTime string formatting: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
John Sheehan
@MasterMax1313: So what? The correct answer should be correct. Using Replace() the way you did in that context was wrong.
Ken White
The fact that it isn't culture agnostic doesn't make it wrong. What's the point of using the extra processing power and memory to make it culture agnostic if it doesn't need to be? How is using Replace() wrong when the requirements don't specify the need?
MasterMax1313
It may not be wrong, but: a) Speaking of extra processing power: Each call to .Replace creates a new temporary string, so there's two useless strings. Not that it matters, but I'd think it negates any gain compared to using the DateTime.ToString(string) overload b) we don't know the culture the person is in and c) even if it works in this content, the poster seems to be new to C#, and I believe it's better to give the proper solution. Nothing against you, but DateTime Formatting WILL haunt you later if done improperly. I've just been through Culture-Specific-Hell, and it wasn't pretty...
Michael Stum
+1  A: 

Try this:

string fileTitle = "testtext.txt";
string fileDirectory = "C:\\Documents and Settings\username\My Documents\";
File.CreateText(fileDirectory + DateTime.Now.ToString("ddMMYYYY") + fileTitle);

?

Andy Mikula
Keep in mind that a DateTime can contain Characters illegal in a Path, for example the forward slash / that some cultures use as a separator.
Michael Stum
Very true! Edited :)
Andy Mikula
+6  A: 
static void WriteToFile(string directory, string name)
{
    string filename = String.Format("{0:yyyy-MM-dd}__{1}", DateTime.Now, name);
    string path = Path.Combine(directory, filename);
    using (StreamWriter sw = File.CreateText(path))
    {
     sw.WriteLine("This is just a test");
    }
}

To call:

WriteToFile(@"C:\mydirectory", "myfilename");

Note a few things:

  • Specify the date with a custom format string, and avoid using characters illegal in NTFS.
  • Prefix strings containing paths with the '@' string literal marker, so you don''t have to escape the backslashes in the path.
  • Combine path parts with Path.Combine(), and avoid mucking around with path separators.
  • Use a using block when creating the StreamWriter; exiting the block will dispose the StreamWriter, and close the file for you automatically.
Michael Petrotta
Wish I could more than +1 on this. Your excellent notes give the answers behind the answer.
JeffH
thank you SO MUCH...this helped a lot
No need for a StreamWriter: File.WriteAllText(path, "This is just a test");
John Sheehan
@John: I was trying to strike a balance between retaining the OP's original content and structure, and suggesting best practices. But yes, absolutely, if you're writing just one line.
Michael Petrotta
I understand. I can't help suggesting less code :)
John Sheehan
Just personal taste, but I'd have put the formatting string inside the original string: string.Format("{0:yyyy-MM-dd}__{1}", DateTime.Now, name);
jerryjvl
@jerryjvl: You're right, that's cleaner. Changed. Thanks!
Michael Petrotta
A: 

To answer the question in your comment on @Scott Ivey's answer: to specify where the file is written to, prepend the desired path to the file name before or in the call to CreateText().

For example:

String path = new String (@"C:\Documents and Settings\bob.jones\Desktop\");
StreamWriter sw = File.CreateText(path + myFileName);

or

String fullFilePath = new String (@"C:\Documents and Settings\bob.jones\Desktop\");
fullFilePath += myFileName;
StreamWriter sw = File.CreateText(fullFilePath);
JeffH