2014-04-27 18 views
0

當我嘗試用我的文本編輯器打開文本文件時,將文本文件拖到我的program.exe上,編輯器打開。但是richtextbox中沒有文本。當我用我的文本編輯器打開它時,如何獲取文本?C#在richtextbox中打開帶有表單和顯示文本的.txt文件

我的想法是這樣的:

if (When u drag file on top of the .exe) 
{ 
    richTextBox.Text = That file u dragged on top of the .exe; 
} 

預先感謝您!

+0

你有什麼問題嗎? – Sayse

+2

[如何將文件拖放到C#應用程序中?](http://stackoverflow.com/questions/68598/how-do-i-drag-and-drop-files-into-ac-sharp -application) – Sayse

+0

我想讓文件中的文本放到我的程序的.exe文件中,然後粘貼該文本介紹我的richTextBox! @Sayse –

回答

0

,你可以做這樣的:

1)去你的表單類,並添加此構造函數:

public Form1(string filename) 
     { 
      InitializeComponent(); 

      //get all the text of text file 
      string[] readText = System.IO.File.ReadAllLines(filename); 
      //insert the string array in your richtextbox 
      foreach (string s in readText) 
      { 
       richTextBox1.Text += s + Environment.NewLine; 
      } 
     } 

2)去你的計劃類和代碼從您的主要變化()方法是:

static void Main(string[] args) 
     { 
      Application.EnableVisualStyles(); 
      Application.SetCompatibleTextRenderingDefault(false); 

      if (args[0] != null) 
      { 
       //args[0] exsists, so a file gets opened 
       //args[0] is the file path 
       Application.Run(new Form1(args[0])); 
      } 
      else 
      { 
       //args[0] doesn't exsist 
       Application.Run(new Form1()); 
      } 
     } 

確保您的主要方法有參數 '字串[] args'!如果你的方法不對,只是在這裏新增

static void Main(string[] args) 

3)建設項目,進入你的.exe文件中的bin文件夾,並通過對.exe文件的頂部下降一個文本文件進行測試(如果我理解你的問題)

+0

不,這不起作用..也許我做錯了什麼,但我不這麼認爲..我做了你所說的我做的 –

+0

@WiebrenddeHaan奇怪,對我來說它是完美的。你有錯誤還是隻是不起作用? – JoJo

+0

你沒有回答他的問題,儘管處理命令行有時也是有用的。他想從外面去掉___滴。 – TaW