Could not create file with variable name using Filestream constructor (C #)

I am trying to create a file with a name that will take today's date as part of the name using the following syntax:

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

It seems that Filestream will not accept a variable path ... What would be the best approach to this?

thank!

+3
source share
2 answers

The problem is that you are creating a path with a built-in slash that ToShortDateString()returns for the culture en-US. In your example, it tries to open the file C:\Test\log12/6/2010.txt, and I suppose the folder C:\Test\log12\6does not exist.

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

+5

HI Aidenn,

. . , . :

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

, ToShortDateString() '/'? . , Win32 CreateFile() , "log12" "5" .

, .

. , MSDN.

-foredecker

+1

Source: https://habr.com/ru/post/1778652/


All Articles