繁体   English   中英

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

[英]Save progress to a text file C#

我在这里有一个问题...所以这就是我想做的:我有一个程序可以保存有关用户进度的信息,例如:呼叫,已接电话...,并且用户每天都运行此程序并将信息保存到文本中文件。 因此,问题在于,当用户点击“保存”按钮时,它会添加当天的新统计信息。 但是我希望如果用户当天保存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
}

谁能帮助我修改当前记录的数据而不丢失以前的记录。 在文本文件中是:

姓名统计_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

我会说使用XML,如果没有代码,它仍然可以读取和修改,并且您有一些巧妙的方法可以用代码修改文件。

使用XML,您可以轻松地查询文件以查看文件中是否已经提到了今天的日期,如果可以,那么您可以编辑该节点,否则就可以轻松地添加节点。

要将节点附加到xml文件,我将查看以下链接: C#,XML,添加新节点

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

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);
    }
}

让我知道如果您需要帮助,或者我理解您的意思不对。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM