實現的代碼以下: public void openfile(int n) { OpenFileDialog openfile = new OpenFileDialog(); openfile.Filter = "*.cs | *.cs";//設置文件後綴
if (openfile.ShowDialog() == DialogResult.OK) { string filename = openfile.FileName; dic1.Add(n, filename); fileArr[n].Text = filename.Substring(filename.LastIndexOf("\\") + 1, filename.LastIndexOf(".") - (filename.LastIndexOf("\\") + 1)); } } 頁面中的【NO】按鈕是用來打開文件的,打開的文件是readonly權限,是不可編寫的,點擊【編輯】按鈕就能夠打開文件而且編輯,實現代碼以下: public void readfile(int btNumber, string mode)//點擊【NO】按鈕,以只讀發方式打開文件
{ int key = Convert.ToInt16(numArr[btNumber].Text) - 1; foreach (KeyValuePair<int, string> kv in dic1) { if (kv.Key == key) { System.IO.FileInfo f = new System.IO.FileInfo(kv.Value); if (mode == "ReadOnly") { f.Attributes = System.IO.FileAttributes.ReadOnly; } System.Diagnostics.Process csProcess = System.Diagnostics.Process.Start(kv.Value); } } } public void readfile(int btNumber)//點擊【編輯】按鈕,以可讀可寫發方式打開文件
{ int key = Convert.ToInt16(numArr[btNumber].Text) - 1; foreach (KeyValuePair<int, string> kv in dic1) { if (kv.Key == key) { System.IO.FileInfo f = new System.IO.FileInfo(kv.Value); f.Attributes = System.IO.FileAttributes.Normal; System.Diagnostics.Process csProcess = System.Diagnostics.Process.Start(kv.Value); } } } 在C#窗體中使用代碼實現文件的打開,用的是進程的思想,即Windows中每一個軟件都是一個進程,咱們平時在電腦中本身打開一個txt文件就是打開一個進程,在代碼中一樣能夠實現打開文件的功能。 關鍵語句就是: System.Diagnostics.Process csProcess = System.Diagnostics.Process.Start(kv.Value); 這裏的kv.Value是用鍵值對把文件名和【NO】中的序號對應起來,方便作一些讀寫操做。 在沒有設置文件的權限時,文件是不可改變的,因此以上代碼中,若是不實現 f.Attributes = System.IO.FileAttributes.ReadOnly; 文件打開後也是不能更改的,你們能夠試試。 爲了使文件可以修改,要設置成 f.Attributes = System.IO.FileAttributes.Normal; 設置文件的屬性主要用到了FileInfo類的Attributes屬性。