13 Replies - 624 Views - Last Post: 30 December 2012 - 02:15 PM Rate Topic: ***** 1 Votes

#1 pundir  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 23-December 12

c# how to open a file with your app

Posted 29 December 2012 - 12:41 PM

so i have a problem regarding opening files with my app.
so the problem is i can't open files when i select "open with > myapp" to open a file, it simply opens my application and doesnt display the contents of the file. i have no code regarding this so if someone could help then it would be great relief.

I will to try explain my problem with an example:

for example there is a text document when we double click it then notepad opens that file and display its contents.
i want my app to do the same.

Is This A Good Question/Topic? 0
  • +

Replies To: c# how to open a file with your app

#2 modi123_1  Icon User is online

  • Suitor #2
  • member icon



Reputation: 9387
  • View blog
  • Posts: 35,242
  • Joined: 12-June 08

Re: c# how to open a file with your app

Posted 29 December 2012 - 12:47 PM

Typically you need to set the file association in windows explorer... and then the file name is passed in the main's args.


static void Main(string[] args)

Was This Post Helpful? 2
  • +
  • -

#3 pundir  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 23-December 12

Re: c# how to open a file with your app

Posted 29 December 2012 - 01:05 PM

thnx for d reply :)

i have done the thing u told n from a little help from here

now i am getting a new error "File format is not valid".

P.S. i have made a simple text editor
Was This Post Helpful? 0
  • +
  • -

#4 modi123_1  Icon User is online

  • Suitor #2
  • member icon



Reputation: 9387
  • View blog
  • Posts: 35,242
  • Joined: 12-June 08

Re: c# how to open a file with your app

Posted 29 December 2012 - 01:26 PM

Okay.. no idea what your code looks like so I don't think help can proceed unless you enlighten us.
Was This Post Helpful? 0
  • +
  • -

#5 pundir  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 23-December 12

Re: c# how to open a file with your app

Posted 29 December 2012 - 01:39 PM

Here is the code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace MyPad
{

    public partial class Form1 : Form
    {
        static string fileloc;

        public Form1()
        {
            InitializeComponent();
        }
        public Form1(string filename)
        {           
            InitializeComponent();
            if (filename != null)
            {
                try
                {
                    richTextBox1.LoadFile(filename);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        

        

       
        void check(ToolStripMenuItem s)
        {
            
            if (s != redToolStripMenuItem)
                redToolStripMenuItem.Checked = false;
            if (s != blackToolStripMenuItem)
                blackToolStripMenuItem.Checked = false;
            if (s != greenToolStripMenuItem)
                greenToolStripMenuItem.Checked = false;
            if (s != blueToolStripMenuItem)
                blueToolStripMenuItem.Checked = false;

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            

        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
         
            TextReader tr;
            openFileDialog1.InitialDirectory = @"D:\test";
            openFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    tr = new StreamReader(openFileDialog1.FileName);
                    richTextBox1.Text = tr.ReadToEnd();
                    tr.Close();
                    fileloc = openFileDialog1.FileName;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "error");
                }
            }
            Text = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
            
        }

        private void wordWrapToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (wordWrapToolStripMenuItem.Checked == true)
                richTextBox1.WordWrap = true;
            else
                richTextBox1.WordWrap = false;
        }

        private void blackToolStripMenuItem_Click(object sender, EventArgs e)
        {
            check(blackToolStripMenuItem);
            richTextBox1.ForeColor = Color.Black;
        }

        private void blueToolStripMenuItem_Click(object sender, EventArgs e)
        {
            check(blueToolStripMenuItem);
            richTextBox1.ForeColor = Color.Blue;
        }

        private void greenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            check(greenToolStripMenuItem);
            richTextBox1.ForeColor = Color.Green;
        }

        private void redToolStripMenuItem_Click(object sender, EventArgs e)
        {
            check(redToolStripMenuItem);
            richTextBox1.ForeColor = Color.Red;
        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
           
            System.Diagnostics.Process.Start(Application.ExecutablePath);
            

        }

        private void MyPad_MouseDoubleClick(object sender, MouseEventArgs e)
        {
           
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                TextWriter tw = new StreamWriter(fileloc);
                tw.Write(richTextBox1.Text);
                tw.Close();
            }
            catch (Exception saveEX)
            {
                MessageBox.Show(saveEX.Message, "error");
            }
        }

        private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
            saveFileDialog1.InitialDirectory = @"D:\test";
            saveFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
            TextWriter tw;
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    tw= new StreamWriter(saveFileDialog1.FileName);
                    tw.Write(richTextBox1.Text);
                    fileloc = openFileDialog1.FileName;
                    tw.Close();
                    fileloc = saveFileDialog1.FileName;
                }
                catch (Exception saveEX)
                {
                    MessageBox.Show(saveEX.Message, "error");
                }
                
            }
            Text = Path.GetFileNameWithoutExtension(saveFileDialog1.FileName);
        }

        private void fontStyleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            fontDialog1.Font = richTextBox1.Font;

            if (fontDialog1.ShowDialog()== DialogResult.OK)
            {
                richTextBox1.Font = fontDialog1.Font;

            }
        }

        private void cutToolStripMenuItem_Click(object sender, EventArgs e)
        {
          
            richTextBox1.Cut();
        }

        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
         
            richTextBox1.Copy();
        }

        private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Paste();
            undoToolStripMenuItem.Enabled = true;
            redoToolStripMenuItem.Enabled = true;
            undoToolStripMenuItem1.Enabled = true;
            redoToolStripMenuItem1.Enabled = true;
        }

        private void undoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Undo();
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Text = richTextBox1.Text.Remove(richTextBox1.Selectionstart, richTextBox1.SelectionLength);
        }

        private void redoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Redo();

        }

        private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            undoToolStripMenuItem.Enabled = true;
            redoToolStripMenuItem.Enabled = true;
            undoToolStripMenuItem1.Enabled = true;
            redoToolStripMenuItem1.Enabled = true;
            
        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            clearToolStripMenuItem.Enabled = true;
            clearToolStripMenuItem1.Enabled = true;
            if (richTextBox1.Text == "")
            {
                clearToolStripMenuItem.Enabled = false;
                clearToolStripMenuItem1.Enabled = false;
            }
           
        }

        private void richTextBox1_Selectionchanged(object sender, EventArgs e)
        {
            if (richTextBox1.SelectedText == "")
            {
                cutToolStripMenuItem.Enabled = false;
                copyToolStripMenuItem.Enabled = false;
                deleteToolStripMenuItem.Enabled = false;
                cutToolStripMenuItem1.Enabled = false;
                copyToolStripMenuItem1.Enabled = false;
                deleteToolStripMenuItem1.Enabled = false;
                
            }
            else
            {
                cutToolStripMenuItem.Enabled = true;
                copyToolStripMenuItem.Enabled = true;
                deleteToolStripMenuItem.Enabled = true;
                cutToolStripMenuItem1.Enabled = true;
                copyToolStripMenuItem1.Enabled = true;
                deleteToolStripMenuItem1.Enabled = true;
              
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();

        }

        private void aboutMyPadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form2 obj = new Form2();
            obj.Show();
            
        }

        private void clearToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Clear();
        }

        private void clearToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            richTextBox1.Clear();
        }

        private void dateAndTimeToolStripMenuItem_Click(object sender, EventArgs e)
        {   
            DateTime date = DateTime.Now;
            TimeSpan time = new TimeSpan(36, 0, 0, 0);
            DateTime combined = date.Add(time);
            richTextBox1.Text = combined.ToString();
        }

       

      

       
    }
}




the error i am getting is due to an exception in "public form1(string)" contructor

this is what i have written in program.cs file

static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            if (args.Length > 0)
                Application.Run(new Form1(args[0]));
            else
                Application.Run(new Form1());
        }


Was This Post Helpful? 0
  • +
  • -

#6 andrewsw  Icon User is online

  • It's just been revoked!
  • member icon

Reputation: 3614
  • View blog
  • Posts: 12,437
  • Joined: 12-December 12

Re: c# how to open a file with your app

Posted 29 December 2012 - 01:58 PM

Output args[0] to check that it is correctly reading the filename :)/>

You may also need to pre-pend the file-path before loading the file, or require that the user supplies the full-path in the commmand-line.

You also need to specify the filename as an optional argument:

public Form1(string filename = "")


richTextBox1.LoadFile(filename)


LoadFile is also expecting to receive an .rtf file (don't know if it will accept .txt?). Actually, Quote: Loads a rich text format (RTF) or standard ASCII text file into the RichTextBox control.

This post has been edited by andrewsw: 29 December 2012 - 02:10 PM

Was This Post Helpful? 1
  • +
  • -

#7 CodingSup3rnatur@l-360  Icon User is online

  • D.I.C Addict
  • member icon

Reputation: 992
  • View blog
  • Posts: 972
  • Joined: 30-September 10

Re: c# how to open a file with your app

Posted 29 December 2012 - 02:04 PM

Quote

args[0] will be the name of your application


I don't think that's correct in C#. The args array passed to Main() only contains what the user explicitly passed to the application.

Environment.GetCommandLineArgs() however, does have the application name as the first argument.

pundir, I think we need to see how you are invoking you program to know for sure what the problem is. Specifically, we need to know what you arguments are passing to the application.
Was This Post Helpful? 0
  • +
  • -

#8 pundir  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 23-December 12

Re: c# how to open a file with your app

Posted 29 December 2012 - 02:13 PM

i passsed arguments as mentioned here

sorry i m a newbie to c# so i have done a simple error :)

instead of building the solution after editing my code i just saved my code ... so after building the solution to the edited code the app works fine :)

sorry for any inconvenience and thnx to every1 for helping me out :)
Was This Post Helpful? 0
  • +
  • -

#9 andrewsw  Icon User is online

  • It's just been revoked!
  • member icon

Reputation: 3614
  • View blog
  • Posts: 12,437
  • Joined: 12-December 12

Re: c# how to open a file with your app

Posted 29 December 2012 - 02:24 PM

Quote

I don't think that's correct in C#. The args array passed to Main() only contains what the user explicitly passed to the application.


Yes, I corrected my post; C# is different to most other languages in this regard.
Was This Post Helpful? 0
  • +
  • -

#10 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3621
  • View blog
  • Posts: 11,276
  • Joined: 05-May 12

Re: c# how to open a file with your app

Posted 29 December 2012 - 03:10 PM

That call to RichTextBox.LoadFile() expects the file to be in RTF format. If your file is not RTF, then I'm not surprised that you are getting that exception.

See MSDN: http://msdn.microsof...y/3f99sst7.aspx
Was This Post Helpful? 1
  • +
  • -

#11 pundir  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 23-December 12

Re: c# how to open a file with your app

Posted 30 December 2012 - 03:13 AM

View PostSkydiver, on 29 December 2012 - 03:10 PM, said:

That call to RichTextBox.LoadFile() expects the file to be in RTF format. If your file is not RTF, then I'm not surprised that you are getting that exception.

See MSDN: http://msdn.microsof...y/3f99sst7.aspx


gr8 observation :)

instead of doing this
 richTextBox1.LoadFile(filename);


do this :
richTextBox1.Text = System.IO.File.ReadAllText(filename);

Was This Post Helpful? 0
  • +
  • -

#12 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3621
  • View blog
  • Posts: 11,276
  • Joined: 05-May 12

Re: c# how to open a file with your app

Posted 30 December 2012 - 10:54 AM

I recommend using the other variant of LoadFile() where you pass in the file type: http://msdn.microsof...y/d76176b1.aspx

Your code:
richTextBox1.Text = System.IO.File.ReadAllText(filename);


is the most inefficient way to load plain text into a RichTextBox.

The ReadAllText() goes into unmanaged code space, allocates memory, reads all the file data, marshals the data to managed space as a string. The assignment to the Text property of the RichTextBox goes and marshals the strings back to unmanaged code space, and the RichEdit control parses the string into lines and allocates its own copies of the lines of text.

Using the other variant of LoadFile() uses the unmanaged EM_STREAMIN that most of the work on the unmanaged side. To read about EM_STREAM see: http://msdn.microsof...2(v=vs.85).aspx )

This post has been edited by Skydiver: 30 December 2012 - 10:55 AM

Was This Post Helpful? 1
  • +
  • -

#13 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2132
  • View blog
  • Posts: 3,263
  • Joined: 21-June 11

Re: c# how to open a file with your app

Posted 30 December 2012 - 01:54 PM

Sorry for going off topic, but

View Postandrewsw, on 29 December 2012 - 10:24 PM, said:

Yes, I corrected my post; C# is different to most other languages in this regard.


Really? That's not my experience.

Languages that I know where the argument list starts with the application name:

  • C/C++
  • OCaml


Languages that I know where the argument list only contains the actual arguments:

  • All JVM languages
  • All .net languages
  • Perl
  • Python
  • Ruby
  • Haskell
  • SML (interesting that the MLs differ here)
  • Racket

Was This Post Helpful? 0
  • +
  • -

#14 andrewsw  Icon User is online

  • It's just been revoked!
  • member icon

Reputation: 3614
  • View blog
  • Posts: 12,437
  • Joined: 12-December 12

Re: c# how to open a file with your app

Posted 30 December 2012 - 02:15 PM

@sepp2k
Point well made :bigsmile:/>. I was thinking (narrowly) in comparison to C and C++, languages that I have dabbled with recently to read the arguments.

I think it a point worth mentioning, and checking, though. The first argument, depending on the language, can be a filename rather that what I might consider the actual arguments. A simple print or MessageBox will confirm the behaviour.

This post has been edited by andrewsw: 30 December 2012 - 02:16 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1