将文件路径存储为 C# 控制台应用程序的变量

发布于 2024-07-15 19:20:56 字数 662 浏览 5 评论 0原文

我正在尝试创建一个将生成日志文件的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

这个俗人 2024-07-22 19:20:56

文件名中不能包含 :。 更好的方法可能是使用类似的格式

YYYYMMDD_HHMMSS.log

(例如 20090323_231245.log)。

这具有易于排序的优点,并且不使用任何无效字符。

您可以使用

string logFile = string.Format("{0:yyyyMMdd_HHmmss}.log", DateTime.Now);

Notes:

获得此信息:此外,正如评论中所建议的,您应该考虑使用 Path.Combine 来组合您的目录和文件名。 这将有助于缓解尾随路径分隔符等问题。

You can't include a : in a filename. A better approach might be to use a format like

YYYYMMDD_HHMMSS.log

(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

string logFile = string.Format("{0:yyyyMMdd_HHmmss}.log", DateTime.Now);

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.

情栀口红 2024-07-22 19:20:56

您还需要在“logDrive”中添加尾部斜杠。 即:

logDrive = "C:\Scripts\ServiceDesk\Logs\"

..或按照其他答案中的建议使用 Path.Combine

You'll also need to add a trailing slash to your 'logDrive'. I.e:

logDrive = "C:\Scripts\ServiceDesk\Logs\"

..or use Path.Combine as suggested in the other answer

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文