将文件路径存储为 C# 控制台应用程序的变量
我正在尝试创建一个将生成日志文件的 C# 控制台应用程序。 我希望在日志文件的存储位置上有一定的灵活性。
我尝试使用 Settings.settings 文件:
名称:logDrive 类型:字符串 范围:应用 值:C:\Scripts\Logs
在我的代码中,我使用:
string logFile = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString();
logFile = logFile.Replace(@"/", @"-").Replace(@"\", @"-") + ".log";
string logDrive = Properties.Settings.Default.logDrive;
StreamWriter output = new StreamWriter(logDrive + logFile);
编译上述内容时,我收到错误消息“不支持给定路径的格式”。
如果有帮助,则值:
logDrive = "C:\Scripts\ServiceDesk\Logs" logFile = "3-23-2009 1:20 PM.log"
有没有人对更好的方法和/或我做错了什么有任何想法/建议?
I'm trying to create a C# console application that will generate a log file. I'd like to have some flexibility with where the log file will be stored.
I tried using the Settings.settings file with:
Name: logDrive
Type: string
Scope: Application
Value: C:\Scripts\Logs
In my code, I'm using:
string logFile = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString();
logFile = logFile.Replace(@"/", @"-").Replace(@"\", @"-") + ".log";
string logDrive = Properties.Settings.Default.logDrive;
StreamWriter output = new StreamWriter(logDrive + logFile);
When compiling the above I get the error message "The given path's format is not support."
If it helps, the values for:
logDrive = "C:\Scripts\ServiceDesk\Logs"
logFile = "3-23-2009 1:20 PM.log"
Does anyone have any thoughts/ recommendations for a better approach and/ or what I'm doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
文件名中不能包含
:
。 更好的方法可能是使用类似的格式(例如
20090323_231245.log
)。这具有易于排序的优点,并且不使用任何无效字符。
您可以使用
Notes:
获得此信息:此外,正如评论中所建议的,您应该考虑使用
Path.Combine
来组合您的目录和文件名。 这将有助于缓解尾随路径分隔符等问题。You can't include a
:
in a filename. A better approach might be to use a format like(e.g.
20090323_231245.log
)This has the benefit of being easily sortable, and it doesn't use any invalid characters.
You can get this using
Notes:
Also, as suggested in the comments, you should consider using
Path.Combine
to combine your directory and filename. This will help mitigate issues with trailing path separators, etc.您还需要在“logDrive”中添加尾部斜杠。 即:
..或按照其他答案中的建议使用 Path.Combine
You'll also need to add a trailing slash to your 'logDrive'. I.e:
..or use Path.Combine as suggested in the other answer