【问题标题】:How to write to a txt file如何写入txt文件
【发布时间】:2015-12-11 11:09:20
【问题描述】:

我有我认为会写入 txt 文件的代码,但它不工作。路径确实存在,但 txt 文件本身不存在,这就是我有“if”语句的原因。我不确定问题出在哪里,因为代码运行和编译没有错误。任何帮助都会很有用。说明:

创建一些执行以下操作的日志记录代码。

创建一个日志类。 字段

文件名

构造函数(字符串) 将文件名设置为参数。 如果文件不存在,则创建该文件。

打开文件并添加一行指示日期的文本。

方法 采用字符串消息和日志级别枚举(调试、警告、信息、错误)的日志方法 此方法将以追加模式打开文件,并使用以下格式将消息和枚举添加为新行:

LogLevel(格式为 6 个字符)时间 (HH:mm:ss.ffff) 消息

主要 创建您的日志对象。 使用警告枚举值调用带有消息的日志对象。 使用调试枚举值调用带有消息的日志对象。 使用 info 枚举值调用带有消息的日志对象。 使用错误枚举值调用带有消息的日志对象。

下面是代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Logging
{
    public class Log
    {
        public enum Levels { Debug, Warn, Info, Error};

        private string path = @"C:\Users\eliotta1130\Desktop\CSharp\Labs\Logging.txt";

        //public string Path { get; set; }
        //public Levels Levels { get; set; }

        public Log(string path)
        {
            this.path = path;
            if(!File.Exists(path))
            {
                File.Create(path);
            }
            StreamWriter textOut = new StreamWriter( new FileStream(
                                                    path, FileMode.Open, FileAccess.Write));
            textOut.WriteLine(DateTime.Now);

            textOut.Close();
        }
        public void tWrite(Levels levels, string message)
        {
            StreamWriter fs = new StreamWriter( new FileStream(path, FileMode.Append, FileAccess.Write));
            fs.WriteLine(string.Format("{0}, {1}", DateTime.Now.ToString("HH:mm:ss.ffff")), message);
            fs.Close();
        }

    }
}

这是我试图调用类对象的地方。

namespace Logging
{
    class Logging
    {
        static void Main(string[] args)
        {
            Log files = new Log("Logging.txt");

            files.tWrite(Log.Levels.Debug , "Fix the problem");
            files.tWrite(Log.Levels.Warn , "Fix the problem");
            files.tWrite(Log.Levels.Info , "Fix the problem");
            files.tWrite(Log.Levels.Error , "Fix the problem");
        }
    }
}

【问题讨论】:

  • 你的fs.WriteLIne(...) 是不是写错字了?括号弄乱了。
  • 你检查哪条路径并说它不写你的文本?似乎您检查了桌面文件,而您应该检查 bin\debug 文件夹中的文件。
  • 由于new Log("Logging.txt"); 没有指定路径,请在解决方案的 bin\debug 文件夹中查找文件。
  • 为什么不能使用 Log4net 而不是手动记录?

标签: c# .net visual-studio


【解决方案1】:

看来代码工作正常。

但由于您使用 "Logging.txt" 不带路径创建文件,因此您的文件将在您的 bin\debug 文件夹中创建,您应该会在那里看到日志。

或者如果你需要桌面路径,你可以使用这个代码:

var fullPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
                            , "Logging.txt")

并使用 fullPath 创建文件。

也可以在文件中追加一行,你可以简单地使用这样的代码:

var outPut = string.Format("{0}, {1}", DateTime.Now.ToString("HH:mm:ss.ffff")), message);
System.IO.File.AppendAllLines(path, new string[]{outPut});

【讨论】:

  • var fullPath 变量去哪儿了?我不清楚把它放在哪里以及替换什么?在说明中,我需要日志对象来获取字符串。 @Reza Aghaei
  • fullPath 传递给Log 的构造函数
【解决方案2】:

你也可以这样写

   using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\eliotta1130\Desktop\CSharp\Labs\Logging.txt", true))
    {
        file.WriteLine(message);
    }

请注意,第二个参数 true 意味着它将您的消息附加到现有文本中。

【讨论】:

    【解决方案3】:

    你可以像下面这样简单地使用:

      File.WriteAllText("your path", "The text to write to the file"); 
    

    或者您可以使用 AppendAllText() 将文本附加到现有文件中

      File.AppendAllText("your path", "The text to write to the file");
    

    File 位于using System.IO; 命名空间下。

    所以你的编码会是这样的:

        public Log(string path)
        {
            this.path = path;
            if(!File.Exists(path))
            {
                File.Create(path);
            }
        }
        public void tWrite(Levels levels, string message)
        {
           string contentToWrite=string.Format("{0}, {1}", DateTime.Now.ToString("HH:mm:ss.ffff")), message);
           File.AppendAllText(path, contentToWrite);
        }
    

    【讨论】:

    • 是的,要是任务这么简单就好了。我们被指示以我发布的方式写入 txt 文件,但我不知何故放错了一段代码或一行代码关闭。我将在这篇文章中添加说明以使其更清晰。 @un-lucky
    猜你喜欢
    • 2012-07-19
    • 2020-04-21
    • 2012-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多