2012-11-14 107 views
1

我在WinForms中开发了一个文本编辑器。你可以从here下载并使用它。它工作正常。但是,当我在Windows资源管理器中右键单击文本文件并尝试打开它时,它不显示它。 我在网上搜索了这个解决方案,但失败了。你能提出一个解决方案吗? 或者我应该使用RichTextBox。 我还尝试使用RichTextBox创建一个简单的测试项目,并使用LoadFile()如何在C#/ WinForms/TextBox中打开文本文件 - mad编辑器

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

这导致文件格式错误。

+2

试看看这里: http://stackoverflow.com/questions/69761/how-to-associate-a-file-extension-to-the-current-executable-in-c-sharp – Sean

+0

文件关联不起作用。我想知道如何访问在Windows资源管理器中选择的文件。谢谢 – Badar

回答

1

我只是解决了这个问题。谢谢你的帮助。
我正在为面临类似问题的未来帮助添加答案。
这里是解决方案:

呼叫从的Form_Load以下方法():

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

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

为了使这项工作,改变主():

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()); 
     } 
    } 
1

的问题是使用:

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

你必须选择一个Rich Text Format (RTF)文件,所以这是因为装载一个普通的文本文件给你的文件格式错误(ArgumentException的)。所以你可以用这种方式加载它:

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

其实我的问题是当我右键点击一个文本文件并点击打开这个程序,然后这个程序应该打开文本文件。实际上显示一个空文本编辑器。我在网上看到的解决方案可能是“var args = Environment.GetCommandLineArgs();”但仍然没有成功。尽我所能。 – Badar

1

好的根据您的意见和代码提供它不会从Windows打开文件。

当Windows向程序发送一个文件以将其打开时,它将它作为第一个参数发送给exe,例如, notepad.exe C:\Users\Sean\Desktop\FileToOpen.txt

您需要使用Environment.CommandLineEnvironment.GetCommandLineArgs()来获取参数。

在这里看到进一步的信息:How do I pass command-line arguments to a WinForms application?

我会在你的窗体的Load事件处理这和参数传递给你的函数:

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

我刚解决了这个问题。谢谢你的帮助。 – Badar

+0

同样为了将来的参考,如果你发布的答案是“这就是我的做法”,你将无法将其标记为答案,基本上不会回答问题。 =] – Sean

相关问题