【问题标题】:Display the name of the current open file in a Windows Form?在 Windows 窗体中显示当前打开文件的名称?
【发布时间】:2013-04-02 00:46:25
【问题描述】:

我正在使用 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。如何在标签中显示“Document.rtf”或任何其他打开的文件标题(名为 filename1)?

【问题讨论】:

  • 为什么将文本设置为文件名,然后用其内容覆盖它......然后加载它?您不想在单独标签中显示文件名吗?
  • 为什么你不能在选择文件后捕获FileName.. 有一个名为FileName 的属性你知道..
  • 为什么忽略异常?删除该 try/catch 块

标签: c# winforms visual-studio-2012 openfiledialog


【解决方案1】:

使用Path.GetFileName Method

string fileName = @"C:\mydir\myfile.ext";
string result = Path.GetFileName(fileName); 
Console.WriteLine(result); // outputs  myfile.ext

更新 1

string fileName = ofd.FileName;
richTextBoxPrintCtrl1.LoadFile(fileName, RichTextBoxStreamType.RichText);
label1.Text = Path.GetFileName(fileName); //  here's your label

【讨论】:

  • 我认为他是在对话框中的文件名之后?
  • 我正在尝试在标签上显示当前打开文件的名称。
  • @CRice 然后他可以将ofd.FileName 传递给变量string fileName = ofd.FileName; 或直接使用ofd.FileName
  • 现在排序。 J W 的更新给出了答案(切换标签和richtextbox 行)。
【解决方案2】:

首先,检查用户是否实际选择了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
    }
}

【讨论】:

  • 应该提到我是编程新手(在大学学习),所以如果我说一些愚蠢的话,请原谅我。
  • 没问题。只需确保检查用户是否接受了文件对话框,否则在未选择文件名时尝试访问文件名会引发异常!
  • 抓到了。刚刚测试了一下,一切都很好。感谢您的帮助。
  • 即使使用 try/catch。检查用户是否单击了确定...您将避免运行不必要的代码并抛出异常,即使您捕获了它们。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-05
  • 2013-09-16
  • 1970-01-01
  • 1970-01-01
  • 2012-09-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多