我有一个列表框,显示文本文件中的行。我怎么能这样做,以便我可以点击列表框中的项目并将其从列表框和文本文件中删除
private void Read()
{
string filePath = @"//Filepath";
List<String> listOfDels = viewlist.listDeliveries();
using (var streamReader = new StreamReader(filePath, Encoding.Default))
{
while (!streamReader.EndOfStream)
{
listOfDels.Add(streamReader.ReadLine());
listBox1.Items.Clear();
listBox1.Items.AddRange(listOfDels.ToArray());
}
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{ //Remove line from txt file
}
答案 0 :(得分:1)
string tempFile = Path.GetTempFileName();
using(var sr = new StreamReader("file.txt"))
{
using(var sw = new StreamWriter(tempFile))
{
string line;
while((line = sr.ReadLine()) != null)
{
if(line != "removeme")
sw.WriteLine(line);
}
}
}
File.Delete("file.txt");
File.Move(tempFile, "file.txt");