3

I'm trying to create a file with a name which would take the "today" date as part of the name, by using the following syntax:

private static FileStream fs = new FileStream(@"C:\Test\log" + DateTime.Now.ToShortDateString() + ".txt", FileMode.OpenOrCreate, FileAccess.Write);

It seems though that Filestream won't take a variable path... What would be a better approach to this?

Thx!

1
  • Do you get an error? What makes you think that it can't take a variable path? Commented Dec 6, 2010 at 2:10

2 Answers 2

5

The issue is that you generating a path with embedded slashes, which ToShortDateString() returns for the en-US culture. In your example, it is trying to open a file C:\Test\log12/6/2010.txt, and I imagine that the folder C:\Test\log12\6 does not exist.

Try using something like DateTime.Now.ToString("yyyyMMdd") to datestamp your files instead.

Sign up to request clarification or add additional context in comments.

Comments

1

HI Aidenn,

The prolem isn't file stream. It is how you are creating the file name. If you put the file name in a variable, you can see it. Here is what it looks like:

"C:\Test\log12/5/2010.txt"

See how the method ToShortDateString() includes the '/' character? Those are valid directory separators. So, the lower level Win32 call to CreateFile() fails since the direcory "log12" and "5" cannot be found.

You need to create a file name tha doesn't contain any invalid file name characters.

See this article Naming Files, Paths, and Namespaces on MSDN.

-foredecker

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.