简体   繁体   中英

How to open a text file in C#/WinForms/TextBox - mad Editor

I have developed a Text Editor in WinForms. you can download it from here and use it. It works fine. But when I right-click a text file in Windows Explorer and try to open it, it doesn't show it. I have searched solution for this on Web, but failed. Can you suggest a resolution to this. Or should I use RichTextBox. I also tried to create a simple Test project with RichTextBox and used LoadFile() .

// Load the contents of the file into the RichTextBox.
richTextBox1.LoadFile(openFile1.FileName, RichTextBoxStreamType.RichText);

This caused a file format error.

The problem is that using:

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

you have to choose a Rich Text Format (RTF) file, so this is because loading a normal text file gives you a file format error (ArgumentException). So you could load it in this way:

string[] lines = System.IO.File.ReadAllLines(openFile1.FileName);
richTextBox1.Lines = lines;

Ok so based on your comments and the code provided it won't open the file from windows.

When windows sends a file to a program to open it, it sends it as the first paramater to the exe, eg notepad.exe C:\\Users\\Sean\\Desktop\\FileToOpen.txt .

You'll need to grab the arguments using Environment.CommandLine or Environment.GetCommandLineArgs() .

See here for further info: How do I pass command-line arguments to a WinForms application?

I would handle this in your form's Load event and pass the argument to your function:

string filename = Environment.GetCommandLineArgs()[0];
richTextBox1.LoadFile(filename, RichTextBoxStreamType.RichText);

I just solved the problem. Thanks for your help.
I am adding answer for future help who face the similar problem.
Here is the solution:

Call the following method from Form_Load():

public void LoadFileFromExplorer()
{
   string[] args = Environment.GetCommandLineArgs();

   if (args.Length > 1)
   {
     string filename1 = Environment.GetCommandLineArgs()[1];
     richTextBox1.LoadFile(filename1, RichTextBoxStreamType.PlainText);
   }
}

To make this work, change Main():

static void Main(String[] args)
    {
        if (args.Length > 0)
        {
            // run as windows app
            Application.EnableVisualStyles();
            Application.Run(new Form1());
        }
        else
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM