Reputation: 41
So i'm making a program that needs to write info from a text box to a txt file then read the info from the txt file in a rich text box. Heres what I have so far.
private void btn_Write_Click(object sender, EventArgs e)
{
if (File.Exists(@"C:\Windows\Temp\" + txt_Key.Text + ".txt"))
MessageBox.Show("File already exists");
System.Diagnostics.Process.Start(@"C:\Windows\Temp\" + txt_Key.Text + ".txt");
else
{
StreamWriter sw = new StreamWriter(@"C:\Windows\Temp\" + txt_Key.Text + ".txt", true);
sw.WriteLine("Dog: " + txt_Name.Text);
txt_Name.Clear();
sw.WriteLine("Owner: " + txt_Owner.Text);
txt_Owner.Clear();
sw.WriteLine("Age: " + nud_Age.Value.ToString());
nud_Age.Value = 0;
sw.WriteLine("Breed: " + cmb_Breed.SelectedItem.ToString());
if (cmb_Breed.SelectedIndex == 0)
{
sw.WriteLine("Sub Specie: " + cmb_Shepard.SelectedItem.ToString());
cmb_Shepard.SelectedIndex = -1;
}
else if (cmb_Breed.SelectedIndex == 7 && ckb_Pedigree.Checked == true)
{
sw.WriteLine("Pedigree: Yes");
}
else if (cmb_Breed.SelectedIndex == 7 && ckb_Pedigree.Checked == false)
{
sw.WriteLine("Pedigree: No");
}
txt_Key.Clear();
sw.WriteLine("Comments: " + txt_Com.Text);
sw.Close();
txt_Com.Clear();
}
}
private void btn_Read_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(@"C:\Windows\Temp\" + txt_Key.Text, true);
rtb_Info.Text = sr.ReadToEnd();
sr.Close();
}
As you can see in my write button I have
StreamWriter sw = new StreamWriter(@"C:\Windows\Temp\" + txt_Key.Text + ".txt", true);
which does work and makes a txt file with the key that I generated but in my read button it says that the file doesn't exist. Any help appreciated.
Upvotes: 2
Views: 73
Reputation: 16956
I suspect, it is because code is clearing txt_Key
Text value after writing to file.
You should think of either removing below line or having a class field and preserving it for next read.
txt_Key.Clear();
I would also suggest use debugger to step in and see what exact path been constructed.
On a side note, it is not advisable to write into an OS folder.
Upvotes: 1