views:

260

answers:

3

This question have been answered. I recommend sumit_programmers solution below. For now, I've removed my code, thinking it's more confusing than helpful. When I've developed it a bit further, perhaps I'll post my code here, with some comments.

You may also be interested in the answer to the question Save text from rich text box with C#. There is an answer that reminds of the accepted answer to this question. The code should work, but it's written by me, so there may be some errors or missing information.


Update: I have improved the code a bit (at least I think so). "Encoding.Default" seems to work with most common encodings, like ANSI. If the encoding is UTF-8 without byte order mark (BOM), it seems "Encoding.Default" doesn't work, though. For more information, go to informit.com/guides. Here's the code I'm using right now:

private void fileOpen_Click(object sender, EventArgs e)
{
  using (OpenFileDialog dlgOpen = new OpenFileDialog())
  {
    try
    {
      // Available file extensions
      dlgOpen.Filter = "All files(*.*)|*.*";
      // Initial directory
      dlgOpen.InitialDirectory = "D:";
      // OpenFileDialog title
      dlgOpen.Title = "Open";
      // Show OpenFileDialog box
      if (dlgOpen.ShowDialog() == DialogResult.OK)
      {
        // Create new StreamReader
        StreamReader sr = new StreamReader(dlgOpen.FileName, Encoding.Default);
        // Get all text from the file
        string str = sr.ReadToEnd();
        // Close the StreamReader
        sr.Close();
        // Show the text in the rich textbox rtbMain
        rtbMain.Text = str;
      }
    }
    catch (Exception errorMsg)
    {
      MessageBox.Show(errorMsg.Message);
    }
  }
}
+3  A: 

Edit: Ok, if you want to open a plain text file, go back to my original solution.

You could just change the MessageBox.Show to the line:

rtfMain.Text = File.ReadAllText(dlg.FileName);

See the doc for ReadAllText for more info.

The try/catch bit is to avoid having your app crash due to unhandled errors (sometimes it might be the best thing to do to just let it crash, but even then you usually want to close it down in a somewhat controlled manner). Especially when working with files, there's a high risk that they'll fail to load for some reason so it might be useful to surround the code with some error handling, for example something like this:

try
{
    rtfMain.Text = File.ReadAllText(dlg.FileName);
}
catch(Exception ex) // should try to avoid catching generic Exception here and use a more specialized one
{
     MessageBox.Show("Failed to open file. Error: " + ex.Message);
}

Old answer below

Edit: I forgot that it's a RichTextBox, so my first answer wasn't as suitable, so it's probably better to do this instead:

You could just change the MessageBox.Show to the line:

rtfMain.LoadFile(dlg.FileName);

Probably adding in suitable try/catch to handle any errors in reading the file.

See the documentation for RichTextBox.LoadFile for a complete sample.

ho1
I tried your code, but it generates the error message "Invalid file format." Because I'm using "dlg.Filter = "All Files (*.*)|*.*|" + "Text Files (*.txt)|*.txt";" in my code, I think I should be able to open any file. Being a C# beginner, I may be wrong, though.
matsolof
Also, I've never used try/catch. I think it has to do with displaying error messages when needed, but I'm not sure. An explantion would be good, not only for my benefit but for other visitors to this page.
matsolof
@matsolof: Answer amended with answers to your comments (So that it can be formatted better)
ho1
Thanks for your efforts! I've tried your new code but got the error messages "The name 'File' and the name 'dlg' does not exist in the current context". What may the reason be? Also, I've already tried the example at msdn you propose, but I couldn't get it to work. Being a C# beginner, I most likely made some stupid mistake, like not changing a variable name that had to be changed. The example code at msdn will most likely be very useful later when I know more about C#. Right now, though, it's more overwhelming than helpful.
matsolof
@matsolof: You need to import the correct libraries for the calls you're making, so you need a `using System.IO;` at the top of the file for it to find the `File`. The missing `dlg` confuse me though, since that's meant to be the variable you declared in your code sample. THe code in my answer should go after the `if` in your code.
ho1
I've added using System.IO; right below the other using statements at the top of the file. I've also put your code after the if statement (which I stupidly enough hadn't before). The code compiles, but I still get the same error message ("Invalid file format"). I'm really confused right now and really don't know what I'm doing, so perhaps it's better to start from scratch. That strategy has usually worked in the past whenever I've got lost.
matsolof
@matsolof: Otherwise edit your question above to add your current code (especially for your `menuFileOpen_Click` method) and note on which exact row the error happens.
ho1
I followed the suggestion above and copied the entire file. How to see on which row the error happens I don't know, though.
matsolof
@matsolof: Ok, you still have the call to `LoadFile` in there, cut out that whole line and replace it with `rtfMain.Text = File.ReadAllText(dlg.FileName);`
ho1
@matsolof: Btw, just to make sure, my understanding is that you're opening a plain text file (a file you can open in notepad), correct?
ho1
The original idea was to be able to open any file. That's probably not the best approach, though, before I know what I'm doing, I realise now.
matsolof
I changed the code to rtfMain.Text = File.ReadAllText(dlg.FileName); The code now works! Thank you so much!!
matsolof
+2  A: 

try{

openFileDialog fd=new openFileDialog();
fd.showDialog();

richTextbox1.LoadFile(fd.FileName);
}
catch(Exception exc)
{
MessageBox.Show(exc.Message);
}

Vinoth
Thanks for your answer! I've tried your code. After some changes (capitalizing some words, changing fd to dlg and changing richTextBox1 to rtfMain), the code compiled. When I tried to open a file, though, the file didn't open. Instead, I got a message box saying "Invalid file format". What may the reason be?
matsolof
ya Rich Text Box only loads file with extension ".rtf"(rich text format-from default extention for Ms WordPad) ... if you want to open some other file extension such as .txt you have to use FileStream class
Vinoth
+7  A: 

Yes, you are getting that error as you are trying to access file that can't be loaded in Rich Text Box. If you want to load a .rtf file you need to add this line

richTextBox1.LoadFile(dlg.FileName, RichTextBoxStreamType.RichText);

and if you want to load .txt file, you need to add this

richTextBox1.LoadFile(dlg.FileName, RichTextBoxStreamType.PlainText);

Sample Code:

 using (OpenFileDialog ofd = new OpenFileDialog())
        {
            try
            {
                ofd.Filter = "Text files (*.txt)|*.txt|RTF files (*.rtf)|*.rtf";
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    if (Path.GetExtension(ofd.FileName) == ".rtf")
                    {
                        richTextBox1.LoadFile(ofd.FileName, RichTextBoxStreamType.RichText);
                    }
                    if (Path.GetExtension(ofd.FileName) == ".txt")
                    {
                        richTextBox1.LoadFile(ofd.FileName, RichTextBoxStreamType.PlainText);
                    }

                }
            }
            catch (Exception ex)
            {
            }
        }
sumit_programmer
Well, I don't see the code been added there. Please add it after you open the dilog box, I will give a sample code, that might help, please see the code, its edited now.
sumit_programmer
I've now tried your code. It works great! Thanks a lot!!
matsolof
Its my pleasure, Happy Coding :)
sumit_programmer
I think the response you get from experienced programmers, like sumit_programmer, on this site is fantastic! I can't emphasize that enough. If you post a question, it seems you can count on swift and accurate answers. You guys deserve an award of some kind.
matsolof
@matsolof :You said right.He is a great programmer.
PrateekSaluja
Thanks so much Prateek, but the fact is that Stackoverflow is full of talented programmers, I am just a very tiny part of it, hope to learn from you all experts and enhance my programming skills. Its a long unending road, just keep walking :)
sumit_programmer
Couldn't agree more with the comments above. It seems if you post a question at stackoverflow.com, you can count on swift and accurate response and learn something. If you happen to know a bit about some computer language or another or about computers in general, you can also help by answering questions. Being a teacher, I find it very rewarding to teach as well as to learn.
matsolof
If you try the code above and it isn't working, it may be because you haven't written `using System.IO;` at the top of the file (right below the other `using` statements). For more on this subject, see ho1:s comment below.
matsolof