我正在創建一個Windows窗體程序。在表格中,我通過文本框插入一些數據,然後將它們寫入文件中。一旦我按下注冊按鈕,我會註冊一行,等等。 例子:刪除整行,如果有一個字
test1|test2|test3...
test4|test5|test6...
在另一種形式我在一個文本框中鍵入一個單詞,如果這個詞是我的文件我想刪除該行。 例如:單詞是test5,所以我將刪除它所在的所有行。我得:
test1|test2|test3...
感謝Medinoc用戶此:
WRITE
ref class MyClass
{
public:
String^ cognome;
String^ nome;
int voto_diploma;
};
//...
List<MyClass^>^ primo = gcnew List<MyClass^>();
//...
MyClass^ myObj = gcnew MyClass();
myObj->cognome = textBox1->Text;
myObj->nome = textBox2->Text;
myObj->voto_diploma = Convert::ToInt32(textBox35->Text);
primo->Add(myObj);
//...
TextWriter ^tw = gcnew StreamWriter(L"primoAnno.txt", true);
for each(MyClass^ obj in primo)
{
//You can use any character or string as separator,
//as long as it's not supposed to appear in the strings.
//Here, I used pipes.
tw->Write(obj->cognome);
tw->Write(L"|");
tw->Write(obj->nome);
tw->Write(L"|");
tw->WriteLine(obj->voto_diploma);
}
tw->Close();
閱讀
MyClass^ ParseMyClass(String^ line)
{
array<String^>^ splitString = line->Split(L'|');
MyClass^ myObj = gcnew MyClass();
myObj->cognome = splitString[0];
myObj->nome = splitString[1];
myObj->voto_diploma = Convert::ToInt32(splitString[2]);
return myObj;
}
DELETE
TextWriter^ tw = gcnew StreamWriter(L"primoAnno2.txt", true);
TextReader^ tr = gcnew StreamReader(L"primoAnno.txt");
String^ line;
while((line=tr->ReadLine()) != nullptr)
{
MyClass^ obj = ParseMyClass(line);
if(obj->cognome != L"cat")
tw->WriteLine(line);
}
tr->Close();
tw->Close();
File::Delete(L"primoAnno.txt");
File::Move(L"primoAnno2.txt", L"primoAnno.txt");
但刪除部分無法正常工作。你能幫我解決嗎?
究竟是什麼問題? 「不正常工作」是一個非常模糊的錯誤描述。 – PeterK
該函數應該寫入所有與另一個文件中的「cat」不同,然後覆蓋原始文件。問題是該功能刪除了所有的內容。順便說一句,如果(obj-> cognome!= textBox2-> Text)tw-> WriteLine(line);因爲我想「保存」永恆希望不同於textbox.thanks – gAeT