在Windows窗体中显示当前打开的文件的名称
本文关键字:文件 窗体 Windows 显示 | 更新日期: 2023-09-27 18:06:49
我正在使用Visual Studio 2012创建一个基本的c#文本编辑软件。
我想在标签中显示打开的文件的名称。
目前,我的OpenFileDialog
代码包括:
OpenFileDialog ofd = new OpenFileDialog();
ofd.ShowDialog();
try
{
richTextBoxPrintCtrl1.Text = ofd.FileName;
StreamReader sr = new StreamReader(richTextBoxPrintCtrl1.Text);
richTextBoxPrintCtrl1.Text = sr.ReadToEnd();
sr.Close();
richTextBoxPrintCtrl1.LoadFile(ofd.FileName, RichTextBoxStreamType.RichText);
}
catch { }
}
比如说,我用这个软件打开Document.rtf。我如何在标签(命名为filename1
)中显示"Document.rtf"或任何其他打开的文件标题?
use Path.GetFileName Method
string fileName = @"C:'mydir'myfile.ext";
string result = Path.GetFileName(fileName);
Console.WriteLine(result); // outputs myfile.ext
- 路径。/ul>
更新1
string fileName = ofd.FileName; richTextBoxPrintCtrl1.LoadFile(fileName, RichTextBoxStreamType.RichText); label1.Text = Path.GetFileName(fileName); // here's your label
首先,检查用户是否实际选择了OpenFileDialog
中的一个文件。然后设置文本:
OpenFileDialog ofd = new OpenFileDialog();
// make sure user selects a file
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
try{
// load contents
richTextBoxPrintCtrl1.LoadFile(ofd.FileName, RichTextBoxStreamType.RichText);
// update label with file name
filename1.Text = System.IO.Path.GetFileName(ofd.FileName);
}catch{
// handle exception as you wish
}
}