C#讀寫TXT文件


讀TXT:

txtpath = System.AppDomain.CurrentDomain.BaseDirectory.ToString() + "test.txt";
if (File.Exists(txtpath))
{
  StreamReader sr = new StreamReader(txtpath, Encoding.UTF8);
  String line;
  while ((line = sr.ReadLine()) != null)
  {
    this.textBox3.Text = line;
  }
  sr.Close();
}

寫TXT:

txtpath = System.AppDomain.CurrentDomain.BaseDirectory.ToString() + "test.txt";if (File.Exists(txtpath))
{
    FileStream stream2 = File.Open(txtpath, FileMode.OpenOrCreate, FileAccess.Write);
    stream2.Seek(0, SeekOrigin.Begin);
    stream2.SetLength(0); //清空txt文件
    StreamWriter sw = new StreamWriter(stream2);
    sw.Write(this.textBox4.Text.ToString());
    sw.Flush();
    sw.Close();
    stream2.Close();
}
else
{
    FileStream fs = new FileStream(txtpath, FileMode.CreateNew);
    StreamWriter sw = new StreamWriter(fs);
    sw.Write(this.textBox4.Text.ToString());
    sw.Flush();
    sw.Close();
    fs.Close();
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM