C# OpenFileDialog的使用

来源:百度知道 编辑:UC知道 时间:2024/09/20 07:04:00
//以下这样使用 OpenFileDialog有什么问题吗?
//为何我使用的时候会有问题!
OpenFileDialog openFileDialog1 = new OpenFileDialog();

openFileDialog1.FileName = "";

openFileDialog1.Filter = "text format.txt|*.txt";
openFileDialog1.ShowDialog();
if ( openFileDialog1.FileName =="") return ;
其实我以上这段代码并没有问题,之所以在我的软件中会出现问题是因为当我调用了
openFileDialog1.ShowDialog(); 后
windows的 System.Environment.CurrentDirectory 值会发生变化,之后我软件所调用的其它的Exe会将System.Environment.CurrentDirectory值 当作其当前路径,而这个软件需要调用当前路径下的一些文件作参数,当System.Environment.CurrentDirectory 发生变化时,这个软件就会出错。
由于这个软件并不是我写的,所以检查了很久才发现问题!总之这种现像非常难遇到,还好搞定了,
谢谢各几位!

openFileDialog1.FileName = ""; 你前面这样写的
if ( openFileDialog1.FileName =="") return ;后面这个条件必然成立,然后跳出
还有就是建议这样写
openFileDialog1.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
或者
if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
string FileName = openFileDialog1.FileName;

}

这样写是不对的,你在添加OPenFileDialog时就生产了一个openFileDialog1,
用的时候 要先写好要打开的路径,比如要存图片就的先写好图片的路径,
string strg=Appliction.StartupPath.Tostring();
strg=strg.Substring(0,strg.LastIndexOf("\\"));
strg=strg.Substring(0,strg.LastIndexOf("\\"));
strg+=@"\项目中存图片的文件夹名"
strg+=@"\default.jpg";
OpenFileDialog1.FileName=strg;

OpenFileDialog openFileDialog1 = new OpenFileDialog();

openFileDialog1.Filter = "text format.txt|*.txt";

if (openFileDialog1.ShowDialog() != DialogResult.OK)