2012-11-11 59 views
1

您可以设置Windows使用Word或其他应用程序打开.doc文件。我如何创建这样一个c#应用程序,它可以处理,如果为了例子我打开一个.txt文件与该应用程序?所以计划是:这里有一个information.kkk这个文件是一个文本文件,里面有一个数字。我想让我的c#应用程序(Visual Studio 2010)接收该数字,如果文件被它打开。用我的c#应用程序打开特定文件 - 就像使用Word打开.doc文件

+1

在[SO here] [1]中有一个较老的答案,似乎涵盖了您的要求。 [1]:http://stackoverflow.com/questions/69761/how-to-associate-a-file-extension-to-the-current-executable-in-c-sharp – renick

+0

同意我正准备粘贴那个,。,。你甜菜我! – FlavorScape

+1

http://stackoverflow.com/questions/2681878/associate-file-extension-with-application这似乎是一个更清洁的方法tho – Machinarius

回答

2

如果你打开一个ddd.txt与您的应用程序(exe文件),那么字符串[] Args将有两个项目:程序的路径本身和ddd.txt路径。以下示例代码显示如何将ddd.txt文件放入文本框Form1。非常感谢大家的帮助。

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows; 
using System.Windows.Forms; 

namespace WindowsFormsApplication1 
{ 
    public partial class Form1 : Form 
    { 
     public static class Environment 
     { 
     } 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

    private void Form1_Load(object sender, EventArgs e) 
    { 
     string[] args = System.Environment.GetCommandLineArgs(); 
     string filePath = args[0]; 
     for (int i = 0; i <= args.Length - 1; i++) 
     { 
      if (args[i].EndsWith(".exe") == false) 
      { 
       textBox1.Text = System.IO.File.ReadAllText(args[i], 
       Encoding.Default); 
      } 
     } 
    } 
    private void Application_Startup(object sender, StartupEventArgs e) 
    { 
     string[] args = System.Environment.GetCommandLineArgs(); 
     string filePath = args[0]; 
    } 


} 
public sealed class StartupEventArgs : EventArgs 
{ 

} 

} 
0
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();    


// Set filter for file extension and default file extension 

dlg.DefaultExt = ".kkk"; 

dlg.Filter = "KKK documents (.kkk)|*.kkk"; 
4

在控制台应用程序中使用main函数中的args参数。第一个参数是打开文件的路径。

例如:

class Program 
{ 
    static void Main(string[] args) 
    { 
     var filePath = args[0]; 

     //... 
    } 
} 

在WPF应用程序中使用Application_Startup事件:

private void Application_Startup(object sender, StartupEventArgs e) 
{ 
    var filePath = e.Args[0]; 
    //... 
} 

或者使用环境类 - 在你的.NET应用程序的任何地方:

string[] args = Environment.GetCommandLineArgs(); 
string filePath = args[0]; 
+0

如果我使用WindowsFormsApplication,该怎么做?它不识别参数部分。 ![image](http://weisza.uw.hu/fajlok/args.png)。 – weiszam

+0

@weiszam:使用Enviroment类(编辑答案)或将参数“string [] args”添加到Main方法(Program.cs) - static void Main(string [] args)。 [示例链接](http://www.blackwasp.co.uk/WindowsFormsStartParams.aspx) – mveith

+0

它现在看起来很完美。我将在下面粘贴一个excample应用程序的代码。非常感谢。 – weiszam

相关问题