2014-04-09 66 views
0

我正在为Windows 8桌面构建应用程序,我正在阅读文本文件,并且想要更改一个特定行,但不知道如何如此,因此我拥有的是文本文件说用c删除文本文件中的特定行#

username|false 
username|false 
username|false 

而我想要删除中间的一行时,这是我到目前为止;

StorageFolder folder = ApplicationData.Current.LocalFolder; 
StorageFile storageFile = await folder.GetFileAsync("students.txt"); 
var text = await Windows.Storage.FileIO.ReadLinesAsync(storageFile); 
var list_false = ""; 

foreach (var line in text) 
{ 
    string name = "" + line.Split('|')[0]; 
    string testTaken = "" + line.Split('|')[1]; 
    if (your_name.Text == name) 
    { 
     if (testTaken == "false") { 
      pageTitle.Text = name; 
      enter_name_grid.Opacity = 0; 
      questions_grid.Opacity = 1; 
      var md = new MessageDialog("Enjoy the test"); 
      await md.ShowAsync(); 
     } 
     else 
     { 
      the_name.Text = "You have already taken the test"; 
      var md1 = new MessageDialog("You have already taken the test"); 
      await md1.ShowAsync(); 
     } 
     return; 
    } 
    else 
    { 
     list_false = "You're not on the list"; 
    } 
} 
if (list_false == "You're not on the list") { 
    var md2 = new MessageDialog("You're not on the list"); 
    await md2.ShowAsync(); 
} 

请帮助,它完美地读取名称,并允许他们接受测试,我只是需要它来删除正确的行。提前致谢!!

+0

你是什么意思“去掉中间线有事时”? – Tarec

+0

@Tarec嗯,当他们输入他们的名字时,如果有匹配,那么我想要删除与他们名字相对应的行 – user3263978

回答

1

要考虑的重要事项是您正在修改文件。所以无论你选择改变,你都需要把它写回文件。

在你的情况下,你选择将整个文件读入内存,这实际上对你有利,像这样的东西,因为你可以删除任何不需要的行并写回文件。但是,使用foreach循环遍历列表时,无法删除项目。

从正在循环的数组中删除项目的最佳做法是使用for循环和相反的循环。这也使得,如果我们有一个List<string>工作更容易去除的东西,比如这样:

var list = new List<string>(text); 
for(int i = text.Length - 1; i >=0; i--) 
{ 
    string line = text[i]; 
    //rest of code 
} 
text = list.ToArray(); 

你的任务的下一部分是删除线。您可以在else声明中这样做,因为这是处理已经参加测试的用户的部分。例如:

the_name.Text = "You have already taken the test"; 
list.RemoveAt(i); 

最后,你的循环之后,你需要写整个事情回文件:

await Windows.Storage.FileIO.WriteLinesAsync(storageFile, text); 
1

阅读文件时,可以将内容存储在列表中。当您的“事情发生”时,您可以删除相应索引处的内容,并将列表保存(覆盖)到文件中。

相关问题