怎么删除原有TXT文件中的记录或者把要输入的记录覆盖带原有的记录
我把原来文档中的记录读出来后对其做完增删改后,再存回去会直接加在后面。。原有的记录还在。。我不想原有记录还存在,怎么把原有记录删除啊
[最优解释]
新建一个文件名一样的Text文件存储,就会自动覆盖
[其他解释]
你是怎么增删改的
改完后替换原文件即可
[其他解释]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Collections;
namespace 学生信息管理系统
{
class studentinfo
{
public string Name;
public int Id;
public bool Sex;
public int Age;
public override string ToString()
{
return Id + " " + Name + " " + Sex + " " + Age;
}
static void menu()
{
Console.WriteLine("1.插入学生信息");
Console.WriteLine("2.查看学生信息");
Console.WriteLine("3.删除学生信息");
Console.WriteLine("4.退出");
}
public void add()
{
Console.Write("请输入学号:");
Id = Convert.ToInt32(Console.ReadLine());
Console.Write("请输入名字:");
Name = Console.ReadLine();
Console.Write("请输入性别(true为男,女为false):");
Sex = Convert.ToBoolean(Console.ReadLine());
Console.Write("请输入年龄:");
Age = Convert.ToInt32(Console.ReadLine());
}
static void Main(string[] args)
{
int choice;
string str="y";
string s1 = null;
string s2 = null;
int a;
int b;
FileStream fs = new FileStream("stuinfo.txt",FileMode.OpenOrCreate,FileAccess.ReadWrite);
StreamWriter w = new StreamWriter(fs);
StreamReader sr = new StreamReader(fs);
StreamReader r1 = new StreamReader(fs);
StreamReader r2 = new StreamReader(fs);
Hashtable h = new Hashtable(10);
while ((s1 = r1.ReadLine()) != null)
{
a = Convert.ToInt32(s1[0] + "" + s1[1] + "" + s1[2] + "" + s1[3] + "" + s1[4] + "" + s1[5] + "" + s1[6] + "" + s1[7]);
h.Add(a, s1);
}
while (true)
{
menu();
Console.WriteLine("请选择操作编号:");
choice = Convert.ToInt32(Console.ReadLine());
switch (choice)
{
case 1:
{
while (str=="y")
{
studentinfo stu = new studentinfo();
stu.add();
h.Add(stu.Id, stu);
Console.Write("还要继续插入么?y/n: ");
str=Console.ReadLine();
}
}
break;
case 2:
{
foreach (object value in h.Values)
{
Console.WriteLine(value.ToString());
}
}
break;
case 3:
{
while ((s2 = r1.ReadLine()) != null)
{
b = Convert.ToInt32(s2[0] + "" + s2[1] + "" + s2[2] + "" + s2[3] + "" + s2[4] + "" + s2[5] + "" + s2[6] + "" + s2[7]);
h.Add(b, s1);
}
Console.Write("请输入要删除的学生信息的学生学号:");
int key = Convert.ToInt32(Console.ReadLine());
h.Remove(key);
}
break;
case 4:
foreach (object value in h.Values)
{
w.WriteLine(value.ToString());
}
w.Close();
return;
}
}
}
}
}