C# 使用Stream Writer在文本文件中写入数据,但如何格式化
我使用此代码添加了一个名称,但它的存储方式如下C# 使用Stream Writer在文本文件中写入数据,但如何格式化,c#,C#,我使用此代码添加了一个名称,但它的存储方式如下 using System; using System.Collections; using System.IO; class FunWithScheduling { public void AddView() { FileStream s = new FieStream("Scheduler.txt",FileMode.Append,FileAccess.Write);
using System;
using System.Collections;
using System.IO;
class FunWithScheduling
{
public void AddView()
{
FileStream s = new FieStream("Scheduler.txt",FileMode.Append,FileAccess.Write);
StreamWriter w = new StreamWriter(s);
Console.WriteLine("Enter the Name of the Person To Be Met:");
string name = Console.ReadLine();
w.Write(name);
w.Flush();
w.Close();
s.Close();
}
public static void Main(string[] args)
{
FunWithScheduling a = new FunWithScheduling();
a.AddView();
}
}
我添加了Shawn,但这就是它被时间卡住的原因。尝试以下可能有用的解决方案
Names Date Time
Sandra 11/18/2013 10.12AM
Denise 12/21/2013 10.10PM
Prnikshenth 11/11/2019 12.00AMShawn
您可能只需要分别检查日期和时间的格式。您需要先写入新行。我还使用语句添加了
,这样您就不必手动调用close
string line = name + "\t" + DateTime.Now.Date.ToString() + "\t" + DateTime.Now.Time.ToString();
w.WriteLine(line );
DateTime.Now.Time.ToString();DateTime.Now.TimeOfDay.ToString();不显式打开流并写入File.WriteAllText(“\n”+name”)怎么样代码>或使用(StreamWriter w=File.AppendText(filename))
。使事情变得更简单。您必须先执行File.ReadAllText
并在变量前面加上前缀,否则File.writealText(“\n”+name”)
会覆盖它。但两者都可以工作,更新了答案。我的意思是文件。AppendAllText
。周六就怪它。哈哈,事情发生了:)你是对的,两种方法都更清晰。无论是什么程序编写的文件都忘记使用WriteLine()而使用Write()取而代之的是,在这个问题上,有一个很好的候选项目。
string line = name + "\t" + DateTime.Now.Date.ToString() + "\t" + DateTime.Now.Time.ToString();
w.WriteLine(line );
using (StreamWriter sw = File.AppendText(@"Scheduler.txt"))
{
sw.Write(Environment.NewLine + name);
}