すべてのインスタンス11?まだプロジェクトを作ってみませんか?手順がわかりませんか?コードを書けませんか?学ぶために以下のリンクをご覧ください!
1.知識ポイント
ファイルを開き、テキスト「方法1」を読みます
StreamReader rd1 = new StreamReader(@” c:\ a.txt”);
while((line = rd1.ReadLine())!= null){Console.WriteLine(line); }
rd1.Close();
ファイルを開き、テキスト「方法2」を読みます
using(StreamReader d1 = new StreamReader(@” c:\ a.txt”)){
文字列行;
while((line = rd1.ReadLine())!= null){
Console.WriteLine(line);
}
}
ファイルを開いてテキストを書く方法1
StreamWriter sw = new StreamWriter(@” c:\ a.txt”);
sw.WriteLine(“蘇州”);
sw.WriteLine(“ 125.3”); sw.Close();
ファイルを開いてテキストを書く方法2
using(StreamWriter sw = new StreamWriter(@” c:\ a.txt”)){
sw.WriteLine(“蘇州”);
sw.WriteLine(“ 125.3”);
}
FileStreamオブジェクトの作成(ファイルを開く)
方法1FileStreamfs= new FileStream(@” c:\ a.txt”、FileMode.Create);
方法2 FileStream fs=File.Create(@”c:\a.txt”);
ファイルの場所
ファイル開始fs.Seek(0、SeekOrigin.Begin);
現在の位置fs.Seek(0、SeekOrigin.Current);
ファイルの終わりfs.Seek(0、SeekOrigin.End);
データの書き込み/読み取り
byte [] info = new UTF8Encoding(true).GetBytes( "A");
fs.Write(info、0、info.Length);//バイトデータを書き込む
バイト[]b=新しいバイト[1024];
fs.Read(b、0、b.Length);//バイトデータを読み取る
ストリームを閉じる
fs.Close();
またはusingステートメントを使用
2.スタイルデザイン
ツールで次のコントロールを選択し ます
3.コードの実装
using System.Windows.Forms; using System.IO; namespace 显示和保存文件 { public partial class Form1 : Form { public Form1() { InitializeComponent(); StartPosition = FormStartPosition.CenterScreen; } //”显示文件”的Click事件的代码 private void button1_Click(object sender, EventArgs e) { string file = textBox1.Text; if (!File.Exists(@file)) MessageBox.Show("文件" + @file + "不存在"); else { int a; FileStream fs = new FileStream(@file, FileMode.Open, FileAccess.Read); richTextBox1.Clear(); a = fs.ReadByte(); while (a != -1) //是否读到文件末尾 { richTextBox1.Text += ((char)a).ToString(); a = fs.ReadByte(); } fs.Close(); } } //”保存文件”的Click事件的代码 private void button2_Click(object sender, EventArgs e) { byte a; string file = textBox1.Text; FileStream fs = new FileStream(@file, FileMode.OpenOrCreate, FileAccess.Write); for (int i = 0; i < richTextBox1.Text.Length; i++) { a = (byte)richTextBox1.Text[i]; fs.WriteByte(a); } fs.Flush(); //将写缓冲区的数据写入内存 fs.Close(); } } }