Scott G

Scott G

  • NA
  • 103
  • 7.7k

The process cannot access the file...used by another process

Nov 5 2018 11:07 AM
I have a listbox that is populated with file names that are selected by the user. I want the user to be able to double click on the selected item and open it once it has been added to the listbox. below is the button click event that adds it to the listbox and the double click event that should open the file which is where I am getting the error.
private void button1_Click(object sender, EventArgs e)
{
System.IO.Stream myStream;
OpenFileDialog openFiledialog1 = new OpenFileDialog();
openFiledialog1.FilterIndex = 2;
openFiledialog1.InitialDirectory = "P:\\mypath\\subfolder";
openFiledialog1.RestoreDirectory = true;
openFiledialog1.Multiselect = true;
openFiledialog1.Title = "Please Select a File";
if (openFiledialog1.ShowDialog() == DialogResult.OK)
{
foreach (String file in openFiledialog1.FileNames)
{
try
{
if ((myStream = openFiledialog1.OpenFile()) != null)
{
using (myStream)
{
lstFiles.Items.Add(file.Substring(52));
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
private void lstFiles_MouseDoubleClick(object sender, EventArgs e)
{
string path = "P:\\mypath\\subfolder\\" + lstFiles.SelectedItem.ToString();
File.Open(path, FileMode.Open);
}

Answers (3)