Home > Blockchain >  OpenFileDialog throwing System.IO.FileNotFoundException before it shows the browse dialog
OpenFileDialog throwing System.IO.FileNotFoundException before it shows the browse dialog

Time:11-16

I started creating a simple OpenFileDialog in .NET 5.0, but I get a System.IO.FileNotFoundException: 'Unable to find the specified file.' exception before I can even see the browse dialog.

The dialog should open when I click on the m_FileUploader button. This is the code I use:

Main.Designer.cs

  // 
  // m_FileUploader
  // 
  this.m_FileUploader.Location = new System.Drawing.Point(508, 17);
  this.m_FileUploader.Name = "m_FileUploader";
  this.m_FileUploader.Size = new System.Drawing.Size(234, 52);
  this.m_FileUploader.TabIndex = 0;
  this.m_FileUploader.Text = "Browse descr_names.txt";
  this.m_FileUploader.UseVisualStyleBackColor = true;
  this.m_FileUploader.Click  = new System.EventHandler(this.FileUploader_Click);
  // 
  // m_OpenFileDialog
  // 
  this.m_OpenFileDialog.Filter = "Names |*descr_names.txt";
  this.m_OpenFileDialog.InitialDirectory = "Documents";
  this.m_OpenFileDialog.Title = "Open descr_names.txt";
  this.m_OpenFileDialog.RestoreDirectory = true;

Main.cs

  private void FileUploader_Click (Object sender, EventArgs e) {
    if (m_OpenFileDialog.ShowDialog() == DialogResult.OK) { // Exception throws here
      // Do stuff with file
    }
  }

When I click continue in debug, the rest of the code is executed correctly, but the standalone executable does not like this exception and stops the application.

What am I forgetting here?

CodePudding user response:

You should be using different value for InitialDirectory, since value Documents might not be handled correctly. Instead you should do:

using System;

// Get path for User's documents folder from .NET
var pathToDocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
this.m_OpenFileDialog.InitialDirectory = pathToDocs;

See documentation for more details about SpecialFolder. Or InitialDirectory documentation.

CodePudding user response:

Thanks to @Neil and @Tatranskymedved I found out that my InitialDirectory was causing the problem.

Changing that line to

this.m_OpenFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

solved the problem. Thank you both for the help.

  • Related