0

I have a Winforms application that creates json from values entered by the user then saves as a text file. After saving the file, the file name (with path) is added to a menu strip so that the user can easily access all created json files. If I click on the menu strip after saving the file, I am receiving the "System.IO.DirectoryNotFoundException: 'Could not find a part of the path" error. However, if I restart the application and click on the file path in the menu strip, the file opens with no problem. I am assuming that even though the file is there, something may be "still resolving" or something because it only occurs if I try to access it during the same "session" in which the file was created.

I save the file like this:

            using (StreamWriter file = File.CreateText(filePath))
        {
            file.Write(json);
        }

I add the path to the menu like this:

        private void AddToApiMenu(string testName, string filePath)
    {
        Form1 frm = new Form1();
        foreach (ToolStripMenuItem item in Form1.menuStrip.Items)
        {
            if (item.Text == "Saved Tests")
            {
                foreach (ToolStripMenuItem subitem in item.DropDownItems)
                {
                    if (subitem.Text == "Current Api Key")
                    {
                        ToolStripMenuItem newItem = new ToolStripMenuItem();
                        newItem.Name = testName;
                        newItem.Text = testName;
                        newItem.Tag = filePath;
                        newItem.Click += new EventHandler(frm.MenuItemClickHandler);
                        subitem.DropDownItems.Add(newItem);
                    }
                }
            }
        }
    }

Using this click event of the menu item, I open the file like this:

using (StreamReader r = new StreamReader(filePath))
        {
            json = r.ReadToEnd();
            testCall = JsonConvert.DeserializeObject<TestModel>(json);
        }

This is where/when I receive the error.

Someone requested to see complete event handler code so here it is:

 public void MenuItemClickHandler(object sender, EventArgs e)
    {
        ToolStripMenuItem clickedItem = (ToolStripMenuItem)sender;
        string filePath = clickedItem.Tag.ToString();
        string jsonFile;
       if(filePath.Contains("Sequences"))
        {
            OpenSequence frm = new OpenSequence(filePath);
            frm.Show();
            FormState.PreviousPage = this;
        }
       else if(filePath.Contains("Tests"))
        {
            OpenTest openTest = new OpenTest(filePath);
            openTest.Show();
            FormState.PreviousPage = this;

        }
       else if(filePath == "mFile")
        {
            DialogResult result = openFileDialog1.ShowDialog();
            dynamic call;
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                jsonFile = Path.GetFullPath(openFileDialog1.FileName);

                if(jsonFile != null)
                {
                    using (StreamReader r = new StreamReader(jsonFile))
                    {
                        jsonFile = r.ReadToEnd();
                        call  = JsonConvert.DeserializeObject<dynamic>(jsonFile);
                    }

                    if(call.SequenceName != null)
                    {
                        OpenSequence frm = new OpenSequence(openFileDialog1.FileName);
                        frm.Show();
                        FormState.PreviousPage = this;
                    }
                    else if(call.MethodName !=null)
                    {
                        OpenTest openTest = new OpenTest(openFileDialog1.FileName);
                        openTest.Show();
                        FormState.PreviousPage = this;

                    }
                }

            }


        }
    }

Is there something I must/can do after performing the file.Write that will make this file immediately accessible from the menu strip without receiving the not found exception?

Any assistance is greatly appreciated.

Rani Radcliff
  • 4,856
  • 5
  • 33
  • 60
  • have you tried `file.Flush()` after you call `file.Write(json)`? – VT Chiew May 06 '19 at 17:02
  • No. I'm unfamiliar with file.Flush(), but I will look it up and try it. Thanks. – Rani Radcliff May 06 '19 at 17:27
  • Tried file.Flush(), but still received the same error when trying to open after save. Thanks for the suggestion though. – Rani Radcliff May 06 '19 at 17:33
  • Have you checked the `filePath` which you open in the event `StreamReader`? I bet it will return `newItem.Name`, right? – k1ll3r8e May 06 '19 at 18:13
  • yes, it shows the complete path which it says it cannot find. I'm not sure what you are asking. – Rani Radcliff May 06 '19 at 18:15
  • I thought, you mistakenly choose the wrong field. But anyways, according to the documentation: `The specified path is invalid, such as being on an unmapped drive.` - Does you store the file on any 'dedicated' storage? (like an super old USB-Stick, slow Network share) – k1ll3r8e May 06 '19 at 18:26
  • It goes to the public folder on the C drive. Remember, it only happens if I 'immediately' try to open it after it is saved. If I stop and restart the application, it works fine. – Rani Radcliff May 06 '19 at 18:29
  • In that case, just try to `Thread.Sleep()` for a few ms (500-1000), after the `using` block. So the System has a bit time to finish the write and cleanup. Maybe that's the prob, you simply try to fast to open it. I had the same prob with `DirectoryInfo.Create()` - added a `Thread.Sleep(500)` and everything was fine. – k1ll3r8e May 06 '19 at 18:33
  • @k1ll3r8e - that didn't work either. It is definitely not a timing issue, because I worked in another part of the application for about 15 minutes before trying to open it and received the error, but as soon as I stopped and started the application, I could open with no problem using the menu strip link. Thanks for your help. – Rani Radcliff May 06 '19 at 19:24
  • You are creating a new instance of the form (`Form1 frm = new Form1();`), updating its menu, then discarding it. Did you mean to update the menu on an existing form? If so, you need to get a reference to the existing one rather than creating a new one. – John Wu May 06 '19 at 19:27
  • @John Wu - I am updating the menu on the existing form (Form1.menuStrip.Items). The instance is used only for the event handler which is firing. Are you saying the event handler is the issue? – Rani Radcliff May 06 '19 at 19:36
  • So the menu on one form fires an event on a different form? That sounds like it is prone to failure. Can you post the complete code for the event handler? – John Wu May 06 '19 at 19:38
  • @John Wu - Event handler code added. – Rani Radcliff May 06 '19 at 19:44
  • i think it would be good to move the `MenuItemClickHandler` out so you need not instantiate a new form just to associate the event handler (though I doubt it caused the error, but no harm trying). Apart from `file.Flush()`, try to add `file.Close()` as well, this should immediately create the file. – VT Chiew May 07 '19 at 06:50

1 Answers1

0

Try this code:

if(!File.Exists(FilePath))
{
    File.Create(FilePath).Close();
}
//Open file code

Source: Unable to access a file that was just created

janavarro
  • 869
  • 5
  • 24