【问题标题】:saving text to a file将文本保存到文件
【发布时间】:2012-09-27 16:46:08
【问题描述】:

我有一个问题让我发疯。我有一个程序将错误消息保存到对象中的字符串中,然后将字符串写入 unloadContent() 事物中的文件。出于某种原因,我不断收到不支持的异常。这是 unloadContent() 中的代码:

        if (debug.getContent().Length > 0)
        {
            saveErrors save = new saveErrors();
            if (Directory.Exists(System.IO.Directory.GetCurrentDirectory() + "\\Errors")) ;
                Directory.CreateDirectory(System.IO.Directory.GetCurrentDirectory() + "\\Errors");
            save.save(System.IO.Directory.GetCurrentDirectory().ToString() + "\\Errors\\errorLog_" + (System.DateTime.Now.ToString().Replace("/", "_")).Replace(" ","") + ".txt");
        }

这是类保存错误中的代码:

    public class saveErrors
    {
        private string mess = debug.getContent();

        public void save(string fileName)
        {
            Debug.WriteLine(fileName);
            using (StreamWriter sw = new StreamWriter(fileName))
            {
                sw.Write(mess);
                sw.Close();
            }
        }
    }

我对 C# 还是有点陌生​​,所以任何帮助都将不胜感激!

谢谢!

【问题讨论】:

  • 哪一行导致错误?
  • “使用 (StreamWriter sw = new StreamWriter(fileName))”行
  • 尝试不使用,只需执行StreamWriter sw = new StreamWriter(fileName) 看看会发生什么
  • 嗯。不行。通常我只会添加一个捕获但我需要日志......啊,编程的乐趣:P
  • 好吧,让我试着编译一下,看看我得到了什么。

标签: c# file stream


【解决方案1】:

试试这个:

[Test]
public void SaveTextTest()
{
    string relativePath=@"Errors\errorLog_";
    string directoryPath = System.IO.Path.Combine( System.IO.Directory.GetCurrentDirectory() , relativePath);
    var directoryInfo = new DirectoryInfo(directoryPath);
    if(directoryInfo.Exists==false)
        directoryInfo.Create();
    string fileName = System.DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss") + ".txt";
    string path = System.IO.Path.Combine(directoryPath, fileName);
    string textToSave = "This will be saved";
    File.WriteAllText(path, textToSave);       
}

要获得所需格式的DateTime.ToString(),您可以传递formatstring

【讨论】:

  • +1 用于展示如何在不使用替换的情况下格式化日期。
  • yyyy-MM-dd_hh-mm-ss是什么概念?
  • 用描述格式字符串使用的链接更新了我的答案。
  • 谢谢!了解方法的概念总比了解方法的类型要好!
【解决方案2】:

save.save(System.IO.Directory.GetCurrentDirectory().ToString() + "\\Errors\\errorLog_" + (System.DateTime.Now.ToString().Replace("/", "_")).Replace(" ", "").Replace(":", "") + ".txt");

改成这样。您需要 .Replace(":", ""),因为 : 包含在代码的日期部分中,但在文件名中无效,因此您必须删除它或将其替换为其他内容。

作为替代方案,您可以这样格式化日期:

save.save(System.IO.Directory.GetCurrentDirectory().ToString() + "\\Errors\\errorLog_" + System.DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss"));

【讨论】:

  • 太棒了!非常感谢!我下次看到错误。对于其他人:该错误是“:”符号不能在路径名中。此外,\Errors\errorLog 应该是 \\Errors\\errorLog。
  • 你的意思是如果(!Directory.Exists...),你应该检查它是否已经存在。
猜你喜欢
  • 2021-12-13
  • 2016-10-28
  • 1970-01-01
  • 1970-01-01
  • 2012-12-31
  • 2012-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多