[英]Create a text file in windows application
我想打開一個文本文件並將一些數據寫入該文件。 這是我的代碼:
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");
這段代碼可以正常工作,但是首先要保存文件。 我希望將文本文件與數據一起打開,並讓用戶保存該文本文件。 可能嗎?
如果我對您的理解正確,則希望程序打開記事本並在其中添加一些文本。 然后,用戶將決定是否保存文件。
在這種情況下,可以使用Process
類啟動記事本。 完成此操作后,您可以觸發一系列鍵盤事件 (模擬按鍵),以便獲得文本。
話雖如此,我認為可能是一種更干凈的解決方案,那就是使用文本區域/文本框打開一個單獨的Form,以便用戶可以通讀。 然后,有一個名為“ Save
的按鈕,該按鈕實際上可以完成您已經在做的事情。
試試這個可以解決你的問題
[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");
}
}
如果希望用戶為文件提供文本,則使用單個文本框構建Windows窗體。 讓用戶鍵入他們想要的任何內容,完成后執行以下操作:
File.WriteAllText(pathToFile, textBox.Text);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.