开发者

Not able to create a file with a variable name using Filestream constructor (C#)

开发者 https://www.devze.com 2023-01-29 04:18 出处:网络
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:

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" + Dat开发者_Python百科eTime.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!


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号