【发布时间】: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