简体   繁体   中英

opening an already existing txt file on button click in c# windows form

My requirement is that when i click a button (C# windows form) of my application,an already existing txt file should get opened in notepad.

I have already tried the above code :

private void btn1_Click(object sender, EventArgs e)
    {
        Process p = new Process();
        String str = txt1.Text;
        ProcessStartInfo ps = new ProcessStartInfo("C:\\Users\\gaurav_joshi\\My Documents\\test.txt");
        ps.UseShellExecute = false;
        ps.RedirectStandardInput = true;

        p.StartInfo = ps;
        p.Start();

        p.StandardInput.Write("This is a test.");
        p.StandardInput.Flush();
        p.StandardInput.Close();
    }

But when i run the program an exception is occuring as follows Win32 Exception "The specified executable is not a valid application for this OS platform"

With streamReader i can read the file but i want to launch the notepad or wordpad itself to read that particular existing file.

Can somebody help me with the above problem

你可以试试这个:

Process.Start("notepad.exe", "C:\\Users\\gaurav_joshi\\My Documents\\test.txt")

All you need to do is use this code:

    Process.Start("C:\\Users\\gaurav_joshi\\My Documents\\test.txt");

You might need this if you don't have it already:

    Using System.Diagnostics;

This will open the text file in your default text editor, to open it in notepad, use this:

    Process.Start("notepad.exe", "C:\\Users\\gaurav_joshi\\My Documents\\test.txt");

You need to execute notepad.exe and pass the file it is to open as a command line argument to it.

If you're trying to invoke behaviour regarding file associations (ie attempting to invoke a .txt file automatically opens it in notepad.exe ), then UseShellExecute=false is not what you want (note link).

Try something like:

Process p = new Process();
ProcessStartInfo ps = new ProcessStartInfo();
ps.FileName = "NotePad.exe";
ps.Arguments = "C:\\Users\\gaurav_joshi\\My Documents\\test.txt";
p.StartInfo = ps;
p.Start();

Try this:

String file_name="c:\\log.txt";
Process.start("notepad",file_name);

尝试这个:

System.Diagnostics.Process.Start("C:\\Users\\gaurav_joshi\\My Documents\\test.txt");

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