目录

​一、OpenFileDialog用法:​

​二、SaveFileDialog用法:​

​三、获取文件路径和文件名、扩展名​

​四、textBox中光标定位到最后一行​


一、OpenFileDialog用法:

private void mi_OpenFile_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog()==DialogResult.OK)
{
_FileName = openFileDialog1.FileName;
System.IO.StreamReader sr;//申明一个流读取器类变量 sr
sr = new System.IO.StreamReader(_FileName,Encoding.UTF8);
textBox1.Text = sr.ReadToEnd();//读取文本文件中的所有数据
sr.Close();

this.Text = _FileName;
_IsSaved = true;
}
}

二、SaveFileDialog用法:

private void SaveTextFile(string fileName)
{
StreamWriter sw = new StreamWriter(fileName);//申明一个流写入器类型的变量sw并实例化了
sw.WriteLine(textBox1.Text);//textBox1中的内容写入sw流中
sw.Flush();//流内容写入磁盘文件中
sw.Close();//最后要关闭写入状态

_IsSaved = true;
this.Text = fileName;
}

private void mi_SaveAs_Click(object sender, EventArgs e)
{
if (_FileName == "")
_FileName = this.Text;

saveFileDialog1.FileName = _FileName;
if(saveFileDialog1.ShowDialog()==DialogResult.OK)
{
_FileName = saveFileDialog1.FileName;
SaveTextFile(_FileName);
}
}

三、获取文件路径和文件名、扩展名

string fullPath = @"e:/xxx/csharp_teach/week09/notepad.exe";

string fileName = System.IO.Path.GetFileName(fullPath);//文件名 “notepad.exe”
string extFile = System.IO.Path.GetExtension(fullPath);//扩展名 “.exe”
string mainFile = System.IO.Path.GetFileNameWithoutExtension(fullPath);// 主文件名(无扩展名) “notepad”