无法在StreamWriter文件名中使用变量

Dal*_*end 0 .net c# windows-mobile

在写入文本文件时,我在Windows Mobile应用程序中收到错误.我首先创建一个文件名:

filename = "IncomingUnit_" + GlobalVar.getDate() + ".txt";
Run Code Online (Sandbox Code Playgroud)

这将以"IncomingUnit_2017053111:22:57.txt"正确打印到控制台.

然后我使用StreamWriter在该文件中写行.

using (System.IO.StreamWriter writer = new System.IO.StreamWriter(filename, true))
{
    foreach (Record _record in records)
    {
        writer.Write(_record);
    }
}
Run Code Online (Sandbox Code Playgroud)

这给了我一个异常,并且没有创建文件:'mscorlib.dll中出现'System.ArgumentException'类型的第一次机会异常'

如果我取出GlobalVar.GetDate,它会创建文件并写入数据.

filename = "IncomingUnit.txt";
Run Code Online (Sandbox Code Playgroud)

如何将日期插入我的文件名?

Vác*_*hár 7

文件名中的冒号":"字符无效.

在StreamWriter中使用它之前,只需将其替换为有效字符:

filename = filename.Replace(":", "_");
Run Code Online (Sandbox Code Playgroud)

根据MSDN,您不能在文件名中使用以下字符:

Tilde (~)
Number sign (#)
Percent (%)
Ampersand (&)
Asterisk (*)
Braces ({ })
Backslash (\)
Colon (:)
Angle brackets (< >)
Question mark (?)
Slash (/)
Plus sign (+)
Pipe (|)
Quotation mark (")
Run Code Online (Sandbox Code Playgroud)