[英]DateTime.Now as file name
I would like to give a document I've created programmatically a name which contains the returned value of DateTime.Now.ToString();
我想提供一个文件,我已经以编程方式创建了一个名称,其中包含
DateTime.Now.ToString();
的返回值DateTime.Now.ToString();
The trial failed when ":" symbol is a content of the file name. “:”符号是文件名的内容时,试用失败。
Any Idea? 任何想法?
Avoid problemw with culture like this 避免像这样的文化问题
DateTime.Now.ToString("yyyy-MMdd-HH-mm", CultureInfo.InvariantCulture)
also you can try out 你也可以尝试一下
string n = string.Format("typeoffile-{0:yyyy-MM-dd_hh-mm-ss-tt}.ext",
DateTime.Now);
try this will work for you 试试这对你有用
String.Replace(".","_")
turn in 转身
DateTime.Now.ToString().Replace(".","_")
I would specify a format for DateTime.ToString()
, for example: 我会为
DateTime.ToString()
指定一种格式,例如:
DateTime.Now.ToString("yyyyMMddhhmmss") //results in "20131127103249"
If you want to go the String.Replace
route, I suggest leveraging a useful method called Path.GetInvalidFileNameChars()
: 如果你想去
String.Replace
路由,我建议利用一个名为Path.GetInvalidFileNameChars()
的有用方法:
string s = DateTime.Now.ToString();
foreach (char c in Path.GetInvalidFileNameChars()) // replace all invalid characters with an underscore
{
s = s.Replace(c, '_');
}
Or, if you're into the whole brevity thing, you can do the same thing in a one-liner using LINQ: 或者,如果你是整个简洁的事情,你可以使用LINQ在单行中做同样的事情:
var s = new String(DateTime.Now.ToString().Select(ch => Path.GetInvalidFileNameChars().Any(invalid => invalid == ch) ? '_' : ch).ToArray());
您可以使用替换功能替换:
例如_
DateTime.Now.ToString().Replace(":","_");
Why don't you try removing the ":" symbol, ie filename will be: 为什么不尝试删除“:”符号,即文件名将是:
20131127_0530 20131127_0530
DateTime.Now.ToString("yyyyddMM_HHmm")
you should be using the custom ToString method specify a formatter ie: 你应该使用自定义ToString方法指定一个格式化程序,即:
DateTime.Now.ToString("ddMMyyyy") - shows daymonthyear DateTime.Now.ToString(“ddMMyyyy”) - 显示为daymonthyear
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.