2013-08-27 97 views
2

我想打開一個文本文件並將一些數據寫入文件。 這裏是我的代碼:在windows應用程序中創建一個文本文件

 FileStream fs1 = new FileStream("D:\\Yourfile.txt", FileMode.OpenOrCreate, FileAccess.Write); 
     StreamWriter writer = new StreamWriter(fs1); 
     writer.Write("Hello"); 
     writer.Close(); 
     System.Diagnostics.Process.Start(@"D:\\Yourfile.txt"); 

此代碼的工作fine.But在這裏第一次將文件保存得到。 我想要一個文本文件隨數據一起打開並讓用戶保存文本文件。 這可能嗎?

+2

你什麼意思,你想用文本文件打開沿數據? –

+1

@neoistheone我認爲OP希望記事本彈出並輸入文本,但尚未保存。 – ispiro

+0

對不起,我的意思是在文本文件裏寫一些文字。 – Priyanka

回答

2

嘗試,這將解決您的問題

 [DllImport("user32.dll", EntryPoint = "FindWindowEx")] 
     public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow); 
     [DllImport("User32.dll")] 
     public static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, string lParam); 
     private void button6_Click(object sender, EventArgs e) 
     {   

      Process[] notepads = Process.GetProcessesByName("notepad"); 
      if (notepads.Length == 0) 
      { 
       Process.Start(@"notepad.exe"); 
       Thread.Sleep(100); 
      } 
      notepads = Process.GetProcessesByName("notepad"); 
       // return; 
      if (notepads[0] != null) 
      { 
       IntPtr child = FindWindowEx(notepads[0].MainWindowHandle, new IntPtr(0), "Edit", null); 
       SendMessage(child, 0x000C, 0, "Hello"); 
      }    

     } 
+0

@Priyanka:這對你有用嗎? – Sumeshk

+0

使用這一行,它只會要求用戶第一次保存它。一旦文件在D:驅動器上創建,它就會直接打開它。我想每次打開一個新的未保存文本文件。並將一些數據寫入它以編程方式。 – Priyanka

+0

@Priyanka:你可以打開記事本的一個實例,獲得窗口的句柄,然後直接寫入文本到那裏。您將需要使用Windows用戶API來執行此操作。 – Sumeshk

3

如果我正確理解你,你會希望你的程序打開記事本並在其中放置一些文本。然後,用戶將決定文件是否被保存。

如果是這樣,您可以使用Process類啓動記事本。一旦你這樣做,你can fire a series of keyboard events(模仿鍵),讓你有文字。

這就是說,我認爲可能是一個更清潔的解決方案將打開一個單獨的窗體與文本區域/文本框,以便用戶可以通讀。然後,有一個名爲Save的按鈕,它基本上做你已經做的事情。

0

如果您希望用戶爲該文件提供文本,請使用單個文本框構建Windows窗體。讓任何他們想要的用戶類型,當你做,這樣做:

File.WriteAllText(pathToFile, textBox.Text); 
相關問題