各位高手,本人最近一直在OpenFileDialog的默认路径上产生很大疑问。本人设置默认路径是 桌面,但再次打开时却变成了打开文件的路径。以下在代码,请各位高手帮忙解答
private void btnExcel2_Click(object sender, EventArgs e)
{
string strPath = System.IO.Directory.GetCurrentDirectory();
OpenFileDialog fd1 = new OpenFileDialog();
fd1.Filter = “Excel_2013(*.xlsx)|*.xlsx|Excel_之前版本(*.xls)|*.xls|全部文件(*.*)|*.*”;
fd1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
fd1.ShowReadOnly = true;
if (fd1.ShowDialog() == DialogResult.OK)
{
Excel.Application eApp2 = new Excel.Application();
Excel.Workbook book = eApp2.Application.Workbooks.Add(fd1.FileNames);
eApp2.Visible = true;
SecondTextPath.Text = fd1.FileName.ToString();
SecondTextPath.ReadOnly = true;
}
else
{
return;
}
private void btnExcel2_Click(object sender, EventArgs e)
{
string strPath = System.IO.Directory.GetCurrentDirectory();
OpenFileDialog fd1 = new OpenFileDialog();
fd1.Filter = “Excel_2013(*.xlsx)|*.xlsx|Excel_之前版本(*.xls)|*.xls|全部文件(*.*)|*.*”;
fd1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
fd1.ShowReadOnly = true;
if (fd1.ShowDialog() == DialogResult.OK)
{
Excel.Application eApp2 = new Excel.Application();
Excel.Workbook book = eApp2.Application.Workbooks.Add(fd1.FileNames);
eApp2.Visible = true;
SecondTextPath.Text = fd1.FileName.ToString();
SecondTextPath.ReadOnly = true;
}
else
{
return;
}
if (fd1.FileName != Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory))
{
MessageBox.Show(fd1.FileName.ToString());
fd1.Reset();
}
}
解决方案
25
去除 fd1.ShowReadOnly = true; 再试试。
5
设置一个全局变量记录上次打开路径,其默认值是桌面。每次打开openFileDialog之前都用这个变量给openFileDialog.FileName赋值,这样关掉后再打开默认路径就是桌面。每次选择了新的路径后再记录下来,打开选择框的时候再用记录的路径赋值设置路径。