2012-11-14 43 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

相關問題