[英]C# Getting StreamWriter to Write to text file
我已經多次復習了我的教授的演講,復習了教科書,在網絡上無休止地尋找答案,並嘗試了所有合理的建議修復方法。 我當然想念一些東西。 通訊簿寫入列表框,創建文件,但名稱和地址未寫入文件。 我所缺少的任何幫助將不勝感激。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.IO;
namespace LAB7A
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
List<Person> people = new List<Person>();
class Person
{
public string Name
{
get;
set;
}
public string Email
{
get;
set;
}
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
StreamWriter address = new StreamWriter("addressbook.txt");
address.WriteLine(textBox1.Text, textBox2.Text);
}
catch (DirectoryNotFoundException exc)
{
MessageBox.Show("Directory Could Not Be Found");
}
}
private void button1_Click(object sender, System.EventArgs e)
{
Person p = new Person();
p.Name = textBox1.Text;
p.Email = textBox2.Text;
people.Add(p);
listBox1.Items.Add(p.Name);
listBox1.Items.Add(p.Email);
//StreamWriter address.WriteLine(textBox1.Text);
//address.WriteLine(textBox2.Text);
//listBox1.Items.Add(textBox1.Text);
//listBox1.Items.Add(textBox2.Text);
}
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
}
}
}
當所有字段為空時,您將在表單加載時將數據保存到文件。 在有機會在文本字段中鍵入值之后,將編寫代碼移動到某些按鈕單擊處理程序。
您還使用版本格式為第一個參數的TextWriter.WriteLine方法的版本。 除非您真的想這樣做,否則2個單獨的WriteLine
調用或一個具有正確格式字符串的調用可能會滿足您的要求。
另外,請確保關閉/處置流編寫器,以便將更改提交到文件並關閉文件。 通常的做法是using
:
using (var writer = new StreamWriter("addressbook.txt"))
{
writer.WriteLine("First textbox:{0}, second:{1}", textBox1.Text, textBox2.Text);
}
嘗試在流上調用“刷新”或“關閉”。 最佳做法是將它包裝在使用中。
using(StreamWriter address = new StreamWriter("addressbook.txt"))
{
...
}
http://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx
向下滾動到示例代碼。
您忘記添加完整的地址,請嘗試以下操作:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
try
{
using (StreamWriter address = new StreamWriter("d:\\addressbook.txt"))//Add correct address
{
address.WriteLine(textBox1.Text + textBox2.Text);
//OR
address.WriteLine(string.Format("Name:{0}, Email:{1}", textBox1.Text, textBox2.Text));
}
}
catch (DirectoryNotFoundException exc)
{
MessageBox.Show("Directory Could Not Be Found");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.