如何在C#中读取和写入文本文件的日期

时间:2016-11-15 00:08:36

标签: c#

我正在构建一个程序,将数据保存到文本文件中并再次检索它以供以后使用。该程序必须具备的功能之一是它必须保存日期和时间。

到目前为止,我使用以下代码来读写这些日期和时间:

//Write dates to text file:
String path = string.Concat(Environment.CurrentDirectory, @"\database\bob.txt");
StreamWriter save = new StreamWriter(path);
DateTime time = DateTime.Now;
save.WriteLine(time);
save.Dispose();

//Read data from text file:
StreamReader reader = new StreamReader(path);
label.Content = reader.ReadLine();
reader.Dispose();

现在,通过这样做,我可以确认日期被保存到文本文件中,但程序没有将其读入标签。反正这是否会读入标签,以便我可以显示日期?

1 个答案:

答案 0 :(得分:0)

通常最好保存一个对象图,而不是像这样零碎地写数据。

如果您可以控制格式(您可以使用它),那么我会建议使用JSON或XML格式。

这是VB,但很容易转换为C#:

class Person : IComparable
{
    string vorname;
    string nachname;
    int age;

    public Person(string vorname, string nachname, int age)
    {
        this.age = age;
        this.nachname = nachname;
        this.vorname = vorname;
    }

    public int CompareTo(object obj)
    {
        Person other = (Person)obj;
        int a = this.age - other.age;

        if (a != 0)
        {
            return -a;
        }
        else
        {
            return age.CompareTo(other.age);
        }
    }

    public override string ToString()
    {
        return vorname + " " + nachname + "\t" + age;
    }        
}

class Program
{
    static void Main(string[] args)
    {
        Person[] peeps = new Person[20];

        try
        {
            StreamReader sr = new StreamReader("inputNames.txt");

            int count = 0;

            while (!sr.EndOfStream)
            {
                string data = sr.ReadLine();
                Console.WriteLine();
                string[] info = data.Split(',');
                peeps[count] = new Person(info[0], info[1], int.Parse(info[2]));

                count++;
            }
            Array.Sort(peeps);
            sr.Close();
        }
        catch(FileNotFoundException e)
        {
            Console.WriteLine(e.Message);
        }

        StreamWriter sw = new StreamWriter("outputNames.txt");

        Console.WriteLine();
        foreach (Person p in peeps)
        {
            Console.WriteLine(p);
            sw.WriteLine(p);
        }
        sw.Close();
    }
}

使用''' JSON, Use NuGet to Install NewtonSoft.Json Imports Newtonsoft.Json Imports System.IO Public Class SomethingIWantToSave Public Shared Function Load(byval path As String) As SomethingIWantToSave Dim result As SomethingIWantToSave = Nothing Dim content As String = String.Empty If File.Exists(path) Then content = File.ReadAllText(path) result = JsonConvert.DeserializeObject(Of SomethingIWantToSave)(content) End If return result End Function Public Sub Save(byval path As String) Dim content As String = JsonConvert.Serialize(Me) File.WriteAllText(path, content) End Sub End Class Use the class like so: ' load existing data Dim data As SomethingIWantToSave = SomethingIWantToSave.Load(Path.Combine("c:\yadda", "yadda", "content.json")) ' make changes if you like. ... ' save data back to disk data.Save(Path.Combine("c:\yadda", "yadda", "content.json")) 类可以将类似的技术用于XML。