实现的代码以下:
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属性。