检查文件中的行是否已过时,如果是,则删除它

时间:2015-10-17 11:18:31

标签: c# android xamarin

我手机上有一个名为records.txt的已保存文件。它的一行看起来像这样:

XY家庭, 2015.11.10。 12:12 2

家庭姓名,日期,时间和其他号码。

现在,当用户打开应用时,我想检查此文件,如果那里有日期,那已经过了,那么就从文本文件中删除该行。

我的逻辑是,首先将行复制到一个字符串数组,然后检查每一个是否通过了日期,如果没有,则将它们复制到一个新的字符串数组中。删除文本文件并使用第二个字符串数组创建一个新文件。

有趣的是,我的代码适用于Windows窗体,但在android上失败。这是:

var path = global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var records = Path.Combine(path.ToString(), "records.txt");

string[] recordLines; // original lines
string[] newLines; // new lines, excluding the obsolete date lines
int counter = 0;

    if (System.IO.File.Exists(records))
    {
          try
          {
                recordLines = System.IO.File.ReadAllLines(records);
                newLines = new string[recordLines.Length];

                foreach(string rl in recordLines)
                {
                      Regex mypattern = new Regex(@"Család, ([ ._0-9A-Za-z-]+) \w");
                      string recordDate = mypattern.Match(rl).Groups[1].Value;
                      DateTime dt = Convert.ToDateTime(recordDate);

                      if (!((dt - DateTime.Today).TotalSeconds < 0))
                      {
                            newLines[counter] = rl;
                            counter++;
                      }
                 }

                 File.Delete(records);                    
                 using (StreamWriter sw = new StreamWriter(records))
                 {
                       foreach(string s in newLines)
                       {
                             sw.WriteLine(s);
                       }
                 }
            }
            catch (Exception)
            {
                  // tba
            }
    }

编辑:甚至没有触及文本文件也失败了。我试图创建一个新的,但它也不会这样做。我认为这意味着数组出了问题。

我设置了两个权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

EDIT2:显然我的手机包裹了文件的行,因此使正则表达式无法使用。我现在正在修理它。

EDIT3:这确实是手机的保存问题,它使文字无法使用。

0 个答案:

没有答案