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.