首页 > 解决方案 > C#在文件中写入文本的非常奇怪的行为

问题描述

我在 C# 中使用以下代码在文件中记录一些文本...

class Logger{

    public void log(String text)
    {
    System.IO.StreamWriter file = new System.IO.StreamWriter(System.IO.Directory.GetCurrentDirectory()+"\\log.txt", true);
        file.WriteLine(DateTime.Now.ToString("yyy-MM-dd HH:mm:ss: " + text.ToString()));
        file.Close();
    }
}

我这样称呼记录器:

Logger logger = new Logger();
logger.log("some text.");

一旦我运行程序,在控制台中似乎一切正常,但在文件中它看起来像:

- 2019-08-02 09:31:32: C:U32er32Danisourcerepo32Free+2e an2 RollouFree+2e an2 RolloubinDebud.C.Repo32ior19 1 Dev20190802_093132_56029iner7ace creae2!
- 2019-08-02 09:31:32: 7ree+2e au7 Dev bed.C.inn!

知道我必须在代码中更改什么吗?我希望文本是可读的:-)

谢谢您的帮助!

问候,丹尼尔

标签: c#file

解决方案


这个:

DateTime.Now.ToString("yyy-MM-dd HH:mm:ss: " + text.ToString())

需要是:

 DateTime.Now.ToString("yyy-MM-dd HH:mm:ss") + ": " + text

您不想运行text日期格式。


推荐阅读