通过openFileDialog将文本文件加载到richTextBox1中 [英] Loading a text file via openFileDialog into a richTextBox1

查看:221
本文介绍了通过openFileDialog将文本文件加载到richTextBox1中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  I一直试图找出如何通过openFileDialogue将文本文件或lua文件加载到Visual
Studio中的C#的richTextBox1控件中。


我希望用户按下一个按钮来浏览文件和当他们选择lua脚本或文本文件时,文本将是
放在richTextBox1中。但是,如果该文件不是lua脚本或文本文件,那么他们将收到一条警告消息:"Lua和仅文本文件!"。


< span style ="color:#454545"> 非常感谢任何帮助,谢谢。



解决方案

Hi Fluffy,


为了满足需要,这里是你可以参考的代码。

 private void btLoad_Click(object sender,EventArgs e)
{
//清除RichTextBox内容
richTextBox1.Clear();
OpenFileDialog ofd = new OpenFileDialog();
if(ofd.ShowDialog()== DialogResult.OK)
{
//判断文件类型
if(System.IO.Path.GetExtension(ofd.FileName) !=" .txt"&& System.IO.Path.GetExtension(ofd.FileName)!=" .lua")
{
//如果没有,请显示警告并返回
MessageBox.Show("仅限Lua和文本文件!");
返回;
}
//获取文件内容
StreamReader sr = new StreamReader(ofd.OpenFile());
字符串行;
while((line = sr.ReadLine())!= null)
{
richTextBox1.Text + = line;
}
}
}

问候,


Kyle


 I have been trying to find out how to load a text file or lua file via openFileDialogue into a richTextBox1 control with C# in Visual Studio.

I want the user to press a button which will browse files and when they choose either a lua script or a text file then the text will be put inside of a richTextBox1. However if the file isn't a lua script or a text file then they will get a warning message saying: "Lua and text files only!".

Any help will be greatly appreciated, thanks.

解决方案

Hi Fluffy,

To achieve the need, here is the code you can refer to.

    private void btLoad_Click(object sender, EventArgs e)
    {
        // Clear RichTextBox content
        richTextBox1.Clear();
        OpenFileDialog ofd = new OpenFileDialog();
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            // judge the file type
            if (System.IO.Path.GetExtension(ofd.FileName) != ".txt" && System.IO.Path.GetExtension(ofd.FileName) != ".lua")
            {
                // if not, show warning and return
                MessageBox.Show("Lua and text files only!");
                return;
            }
            // get file content
            StreamReader sr = new StreamReader(ofd.OpenFile());
            String line;
            while ((line = sr.ReadLine()) != null)
            {
                richTextBox1.Text += line;
            }
        }
    }

Regards,

Kyle


这篇关于通过openFileDialog将文本文件加载到richTextBox1中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆