开发者

How to disable OpenFileDialog opening files automatically?

I am using following code to select a file to import in a Windows Forms project.

OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "C# Corner Open File Dialog";
fdlg.InitialDirectory = @"c:\";
fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
fdlg.FilterIndex = 2;
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
{
    txtpath.Text = fdlg.FileName;
}

The problem is that the selected file is opened in the background which I don't want. What can I do to just get the pat开发者_如何学Goh of selected file without opening it?


Showing an OpenFileDialog and the user selecting a file does not open the file. The file can be opened by calling OpenFile. In the code you posted the file is not opened. That code appears to be copied from an example on MSDN. The rest of the code from that example is here:

if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
    try
    {
        if ((myStream = openFileDialog1.OpenFile()) != null)  // File is opened here.
        {
            using (myStream)
            {
                // Insert code to read the stream here.
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error: Could not read file from disk. Original error: " +
                        ex.Message);
    }
}

If the file is being opened when you don't want it opened then the problem must be somewhere else and not in the code you posted. It is possible for example that you have not closed the file (for example by using Dispose) after you finished using it last time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜