c# - 在 C# 应用程序中打开文本文件

标签 c#

在编程方面我仍然是初学者,这是我按照 C# 教程开发的一个小应用程序。

private void viewImagesToolStripMenuItem_Click(object sender, EventArgs e)
     {

string openedfile = "";

        openfd.Title = "Insert a text file";
        openfd.InitialDirectory = "C:";
        openfd.FileName = "";
        openfd.Filter = "text files|*.txt|word documents|*.doc|allfiles|*.*";


        if (openfd.ShowDialog() == DialogResult.Cancel)

        {
            MessageBox.Show("Operation canceled");
        }

        if (openfd.ShowDialog() != DialogResult.Cancel)

        {
            openedfile = openfd.FileName;
            richTextBox1.LoadFile(openedfile,RichTextBoxStreamType.PlainText);
        }

在执行此操作时,我注意到如果我仅更改同一个应用程序的代码顺序 2 行 -

   string openedfile = "";
   openedfile = openfd.FileName; 

像下面这样它会在调试时抛出这样的错误——空路径名是不合法的。

    private void openToolStripMenuItem_Click(object sender, EventArgs e)
    {


        openfd.Title = "Insert a text file";
        openfd.InitialDirectory = "C:";
        openfd.FileName = "";
        openfd.Filter = "text files|*.txt|word documents|*.doc|allfiles|*.*";

        **string openedfile = "";
        openedfile = openfd.FileName;**


        if (openfd.ShowDialog() == DialogResult.Cancel)

        {
            MessageBox.Show("Operation canceled");
        }

        if (openfd.ShowDialog() != DialogResult.Cancel)

        {

            richTextBox1.LoadFile(openedfile,RichTextBoxStreamType.PlainText);
        }

没有办法理解这些类型情况下的错误。编写这样的应用程序的具体顺序是什么?

最佳答案

好吧,这个想法很简单,你不能使用一个没有被初始化的变量。 在你的情况下,同样的事情正在发生。 在你的第一个代码中 openedfile = openfd.FileName;对话显示后正在执行。因此文件名正确。 但是在第二个 openedfile = openfd.FileName;在显示对话之前正在初始化。由于没有对话,名称为空,因此会出错。

注意。我没有以技术方式使用初始化词。

关于c# - 在 C# 应用程序中打开文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16476882/

相关文章:

c# - 设置外部应用程序焦点

c# - 在生成的部分类上使用 XmlIgnore

c# - 从 Java 迁移到 C#

c# - ADO.NET CommandBuilder、InsertCommand 和默认约束

c# - 在 C# 中,如何检测数组中的元素何时为空? (当为空时,element = 0)

c# - 有没有办法指定自定义依赖属性的默认绑定(bind)模式和更新触发器?

c# - 所有的逻辑应该写在 Controller 里面?

c# - 使用 web.config 转换在 vs2012 中进行本地部署

C# Linq 查找具有多个分组依据的重复项

c# - 您能否以编程方式查看 USB 设备在 Windows 中请求的安培数?