最近在做一个项目,需要打开在软件中点击按钮,从而打开一个文件,新手学习C#,从此把之后总结的C#的点点知识都总结起来,虽然不是主要做C#上位机的开发,但是多学点东西总是没错,往后会不定期一点点记录自己所学到的知识,希望以后的自己慢慢强大起来。
先来说说现在做的这个界面,如下图所示:
这个界面中,点击【打开】按钮可以选择要打开的文件,如下图所示:
这里涉及一个控件的知识了,就是OpenFileDialog。
选中打开的文件后,实现的功能是把选择的文件的名字填入【文件名】中:
实现的代码如下:
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属性。
Kyrie Irving___全.
更多推荐
<C#>_在窗体中打开文件
发布评论