开发者

Saving formatted timestring as file name problem in c#

开发者 https://www.devze.com 2023-02-11 16:53 出处:网络
HI guys, I only started c# recently so I\'m not 100% familiar with it\'s syntax yet and I got into a problem. I\'d like to write the current time into a filename. I\'m using the following code:

HI guys, I only started c# recently so I'm not 100% familiar with it's syntax yet and I got into a problem. I'd like to write the current time into a filename. I'm using the following code:

DateTime now = DateTime.now;
string dateString = string.Format(@"Z:\test\{0}.bmp",now.ToString("s"));
bitmap.Save(dateString);

Now this gives me a can't access filepath error. Apparently it has somethin开发者_如何学运维g to do with the ":" characters at the time part (at least when I give a now.ToString("d") ) it saves fine. Any idea whats causing this? Thanks.


The "s" format will create a filename of something like:

2009-06-15T13:45:30.bmp

That's just not a valid filename, due to the colon. Either replace the colon with another character after calling ToString, or use a different format.

Note that "d" won't always work either, as it can include "/" in the name, depending on the culture.

Personally I'd suggest something like "yyyyMMdd-HHmmss" which will give you something like

20090615-134530.bmp


Regardless of the code, the Windows filesystems won't allow the use of a colon (or several other "special" characters) in a filename. So the issue is happening at the OS level, not in your code.

You'll want to strip out those characters and/or format the timestamp differently to use it as a filename.


Some characters are not valid in filenames on Windows - See this link. This is not related to c#.


That is caused by the Windows file system, which disallows :'s in file names.


':' are invalid characters for naming a file. You'll need to determine some other valid character to substitute for ':' before attempting to save the file.


public static class SPStringUtils
{
    public static string MakeFilename(this DateTime dt)
    {
        return dt.ToString("yyyyMMdd-HHmmss");
    }

    public static string MakeFilename(this DateTime dt, string format)
    {
        return string.Format(format, MakeFilename(Now));
    }
}

...
Console.WriteLine(Now.MakeFilename(@"c:\logs\log{0}.log");


There can't be no ':' in a file name, that's why.

0

精彩评论

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