将进度保存到文本文件C#

时间:2013-11-28 07:17:41

标签: c#

我在这里遇到问题......所以我想做的就是: 我有一个程序可以保存有关用户进度的信息,例如:呼叫,已应答的呼叫......以及用户每天运行此程序并将iformation保存到文本文件中。所以问题是,当用户点击“保存”按钮时,它会添加当天的新统计信息。但是如果用户在当天保存2次,我希望修改这些数据。 我想做的是创建一个新文件,保存最后一次保存的日期,如果日期不同,则附加到文件,否则修改当天保存的现有文件。

到目前为止我所做的是:

string input3 = string.Format("{0:yyyy-MM-dd}", DateTime.Now);
StreamWriter t,tw;
if(File.Exists(filename))
{
    tw=File.AppendText(filename);
    t = new StreamWriter("lasttimesaved.txt");
    t.WriteLine(input3);
}
else
{
    tw=new StreamWriter(filename);
    t = new StreamWriter("lasttimesaved.txt");
    t.WriteLine(input3);
}

tw.WriteLine();
tw.Write("Stats for Name ");
tw.Write(input);
tw.Write("_");
tw.WriteLine(input3);
tw.WriteLine();
tw.Write("Total Calls: "); tw.WriteLine(calls);
tw.Write("Total Answered: "); tw.WriteLine(answ);
tw.Close();

现在我唯一不知道要做的是如何添加一个检查实例以查看用户是否已经保存了今天的信息并修改现有数据。

就像:

try
{
    using (StreamReader sr = new StreamReader("lasttimesaved.txt"))
    {
        String line = sr.ReadToEnd();
    }
}
catch (Exception e)
{
    Console.WriteLine("The file could not be read:");
    Console.WriteLine(e.Message);
}

if(String.Compare(input3,line) == 0)
{
    // that's where I need to modify the existing data.
}
else 
{
    // do the code above
}

任何人都可以帮我修改当前记录的数据,而不会丢失以前的记录。 在文本文件中是:

Name_2013-11-26的统计资料

Total Calls: 25
Total Answered: 17

Stats for Name_2013-11-27

Total Calls: 32
Total Answered: 15

Stats for Name_2013-11-28

Total Calls: 27
Total Answered: 13

2 个答案:

答案 0 :(得分:0)

我想说使用XML,它仍然可以在没有代码的情况下读取和修改,你可以用一些简洁的方法用代码修改文件。

使用XML,您可以轻松查询文件以查看文件中是否已提及今天的日期,如果是,您可以编辑该节点,否则您可以轻松附加节点。

要将节点附加到xml文件,我会查看此链接: C#, XML, adding new nodes

答案 1 :(得分:0)

希望这有帮助,像这里一样使用它:

void main()
{
   var uw = new UserInformationWriter(@"C:\temp\stats.txt");
   var user = new UserInfomration { Calls = "111", Answered = "110" };
   uw.Save(user);
}

这里的课程:

public class UserInformationWriter
{
    public string CentralFile { get; set; }

    public UserInformationWriter(string centraFile)
    {
        CentralFile = centraFile;
    }

    public void Save(UserInfomration newUserInformation)
    {
        try
        {
            var streamReader = new StreamReader(CentralFile);
            var sourceInformation = streamReader.ReadToEnd();
            streamReader.Close();
            var userCollection = (List<UserInfomration>)(sourceInformation.ToUserInfomation());
            var checkItem = ShouldModify(userCollection);
            if (checkItem.Item1)
                userCollection.Remove(checkItem.Item2);

            newUserInformation.DateTime = DateTime.Today;
            userCollection.Add(newUserInformation);
            File.Delete(CentralFile);
            foreach (var userInfomration in userCollection)
                WriteToFile(userInfomration);
        }
        catch (Exception) { }
    }
    private Tuple<bool, UserInfomration> ShouldModify(IEnumerable<UserInfomration> userInfomations)
    {
        try
        {
            foreach (var userInfomration in userInfomations)
                if (userInfomration.DateTime == DateTime.Today)
                    return new Tuple<bool, UserInfomration>(true, userInfomration);
        }
        catch (Exception) { }
        return new Tuple<bool, UserInfomration>(false, null);
    }

    private void WriteToFile(UserInfomration newUserInformation)
    {
        using (var tw = new StreamWriter(CentralFile, true))
        {
            tw.WriteLine("*Stats for Name_{0}", newUserInformation.DateTime.ToShortDateString());
            tw.WriteLine();
            tw.WriteLine("*Total Calls: {0}", newUserInformation.Calls);
            tw.WriteLine("*Total Answered: {0}#", newUserInformation.Answered);
            tw.WriteLine();
        }
    }
}

public class UserInfomration
{
    public DateTime DateTime { get; set; }
    public string Calls { get; set; }
    public string Answered { get; set; }
}

public static class StringExtension
{
    private const string CallText = "TotalCalls:";
    private const string AnsweredText = "TotalAnswered:";
    private const string StatsForName = "StatsforName_";
    private const char ClassSeperator = '#';
    private const char ItemSeperator = '*';

    public static IEnumerable<UserInfomration> ToUserInfomation(this string input)
    {
        var splited = input.RemoveUnneededStuff().Split(ClassSeperator);
        splited = splited.Where(x => !string.IsNullOrEmpty(x)).ToArray();

        var userInformationResult = new List<UserInfomration>();

        foreach (var item in splited)
        {
            if (string.IsNullOrEmpty(item)) continue;
            var splitedInformation = item.Split(ItemSeperator);
            splitedInformation = splitedInformation.Where(x => !string.IsNullOrEmpty(x)).ToArray();

            var userInformation = new UserInfomration
            {
                DateTime = ConvertStringToDateTime(splitedInformation[0]),
                Calls = splitedInformation[1].Substring(CallText.Length),
                Answered = splitedInformation[2].Substring(AnsweredText.Length)
            };
            userInformationResult.Add(userInformation);
        }
        return userInformationResult;
    }
    private static DateTime ConvertStringToDateTime(string input)
    {
        var date = input.Substring(StatsForName.Length);
        return DateTime.ParseExact(date, "dd.MM.yyyy", CultureInfo.InvariantCulture);
    }

    private static string RemoveUnneededStuff(this string input)
    {
        input = input.Replace("\n", String.Empty);
        input = input.Replace("\r", String.Empty);
        input = input.Replace("\t", String.Empty);
        return input.Replace(" ", string.Empty);
    }
}

让我知道如果你需要帮助或我理解你错了。